diff --git a/.github/workflows/pre-release-tests.yml b/.github/workflows/pre-release-tests.yml new file mode 100644 index 00000000000..2325863da39 --- /dev/null +++ b/.github/workflows/pre-release-tests.yml @@ -0,0 +1,27 @@ +name: Pre-release Tests + +on: + pull_request: + branches: + - main + push: + branches: + - main + +jobs: + build: + runs-on: ubuntu-latest + if: github.ref_name == 'release-please--branches--main' || github.head_ref == 'release-please--branches--main' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '21' + cache: 'maven' + - name: Install Root + run: mvn -B -ntp install -DskipTests -Djacoco.skip=true -Dclirr.skip=true + - name: Compile Examples + run: mvn -B -ntp compile -f examples/pom.xml + - name: Generate Javadoc + run: mvn -B -ntp package -DperformRelease=true -DskipTests -Djacoco.skip=true -Dclirr.skip=true \ No newline at end of file diff --git a/.github/workflows/publish-javadoc.yml b/.github/workflows/publish-javadoc.yml index 2c763bfb2cf..7c18f72053d 100644 --- a/.github/workflows/publish-javadoc.yml +++ b/.github/workflows/publish-javadoc.yml @@ -20,4 +20,4 @@ jobs: java-version: 17 target-folder: javadoc project: maven - custom-command: mvn javadoc:javadoc \ No newline at end of file + custom-command: mvn dokka:javadoc \ No newline at end of file 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 7ffb0c9a55c..d2fd993b39c 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -14,10 +14,9 @@ jobs: strategy: matrix: java: [8, 11, 17, 21] - testgroup: [ - # Includes everything in tests/ except the ones listed here - '**/*,!com.google.genai.ClientTest,!com.google.genai.TableTest,!com.google.genai.HttpApiClientTest,!com.google.genai.ModelsTest,!com.google.genai.OperationsTest' - ] + # Only run unit tests. + testgroup: ["**/*Test"] + fail-fast: false name: unit-test (${{matrix.java}}) steps: - uses: actions/checkout@v4 @@ -27,6 +26,4 @@ jobs: java-version: ${{matrix.java}} cache: 'maven' - name: Java Unit Tests - run: mvn clean test -Dtest=${{matrix.testgroup}} - env: - GOOGLE_API_KEY: testkey + run: mvn clean test -Dtest=${{matrix.testgroup}} -Djacoco.skip=true \ No newline at end of file diff --git a/.github/workflows/validation-java-version.yml b/.github/workflows/validation-java-version.yml deleted file mode 100644 index 9c62d4b2b35..00000000000 --- a/.github/workflows/validation-java-version.yml +++ /dev/null @@ -1,27 +0,0 @@ -# This workflow runs a simple test to verify we are supporing the required Java versions. -name: validation - -on: - pull_request: - branches: - - main - -jobs: - java-version: - runs-on: ubuntu-latest - strategy: - matrix: - java-version: ['8', '11', '17', '21'] - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Set up Java ${{ matrix.java-version }} - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: ${{ matrix.java-version }} - - - name: Compile ${{ matrix.java-version }} - run: mvn clean compile \ No newline at end of file diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 2a8f4ffddf0..0b97f7533e3 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.3.0" + ".": "1.53.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 104a782e62a..541c7639398 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,670 @@ # Changelog +## [1.53.0](https://github.com/googleapis/java-genai/compare/v1.52.0...v1.53.0) (2026-05-05) + + +### Features + +* [Python] Multimodal file search ([b12cd29](https://github.com/googleapis/java-genai/commit/b12cd29933be12951f159052ec519480f6559fe3)) +* Multimodal file search ([aaf0c40](https://github.com/googleapis/java-genai/commit/aaf0c40d15cc9c8a128d75c7fa71c6f9fb6ea480)) + +## [1.52.0](https://github.com/googleapis/java-genai/compare/v1.51.0...v1.52.0) (2026-04-30) + + +### Features + +* [Interactions] Add FileCitation.{custom_metadata,media_id,page_number} ([a09716e](https://github.com/googleapis/java-genai/commit/a09716e170ff952c7587dc8a16c06852219c725e)) +* Add `output_info` to `BatchJob` ([e337ba9](https://github.com/googleapis/java-genai/commit/e337ba96df0ce919fe90481c2324e7c5505a2101)) +* Add ImageResizeMode for GenerateVideos ([e089fcb](https://github.com/googleapis/java-genai/commit/e089fcb3d99a03cc1ecb7786b8ef58966c25ac4d)) +* Add new Gemini Deep Research agent models ([88d7019](https://github.com/googleapis/java-genai/commit/88d7019fee1be2445c070b3d2fdc23f891764fb0)) +* Add Vertex Dataset input and output options for batch jobs ([612601d](https://github.com/googleapis/java-genai/commit/612601da1c5b26f7650bc148124cb568ee52af67)) +* **interaction-api:** Add grounding tool usage breakdown to Interaction Usage. ([bc2f815](https://github.com/googleapis/java-genai/commit/bc2f815b8bd9a9a4f439ca2619fb9208fe3867bd)) +* introduce enterprise and GOOGLE_GENAI_USE_ENTERPRISE ([97adcd9](https://github.com/googleapis/java-genai/commit/97adcd91cbe9b7c13ed6dfdf476d709b99804572)) +* Replace the more ambiguous rate field with sample_rate. ([d762b6e](https://github.com/googleapis/java-genai/commit/d762b6e2fd91e11201dfc84d856fbd2a8e657951)) + + +### Documentation + +* replace Vertex AI with Gemini Enterprise Agent Platform ([84c1d43](https://github.com/googleapis/java-genai/commit/84c1d4328fd3827e26f5d1a2367435fa6ab12a35)) +* update doc string to replace `Vertex AI` with `Gemini Enterprise Agent Platform`, update method error message to replace `Vertex AI` with `Gemini Enterprise Agent Platform (previously known as Vertex AI)`, update converter error message to replace `Vertex AI` with `Gemini Enterprise Agent Platform` ([c5aefa7](https://github.com/googleapis/java-genai/commit/c5aefa754b75330d018993866d798c3dec23a19a)) +* update Gemini Enterprise Agent Platform home page url ([7b46a6f](https://github.com/googleapis/java-genai/commit/7b46a6fdd08a6a80dc2f2bfe8b194264fca2191f)) + +## [1.51.0](https://github.com/googleapis/java-genai/compare/v1.50.0...v1.51.0) (2026-04-16) + + +### Features + +* Add gemini-3.1-flash-tts-preview model to options ([d9a5733](https://github.com/googleapis/java-genai/commit/d9a573332ebefdf385a088360bf3eb5cc889a5a2)) + + +### Bug Fixes + +* ResponseStream fails to parse error message and multi-line SSE data payloads ([3a1cb22](https://github.com/googleapis/java-genai/commit/3a1cb226bc31f5528a56a2d9fd62fcfe89ca77e1)) + + +## [1.50.0](https://github.com/googleapis/java-genai/compare/v1.49.0...v1.50.0) (2026-04-14) + + +### Features + +* [Experimental] Add interactions support. ([abc1ee4](https://github.com/googleapis/java-genai/commit/abc1ee4b47c1af5fe7da9f98ce64fe4c7e3fcec7)) +* Add "eu" as a supported service location for Vertex AI platform. ([78e1bc1](https://github.com/googleapis/java-genai/commit/78e1bc19d154ba5dad4e4986a9d6e7f8a6c585b8)) +* Add Live Avatar new fields ([8e8146a](https://github.com/googleapis/java-genai/commit/8e8146a3a8d6d37e8fe691a6f96e7fd2b055d988)) +* Add webhook_config to batches.create() and models.generate_videos() ([ac0e49e](https://github.com/googleapis/java-genai/commit/ac0e49e187ecbda2b58d10e60161b3ab6fd24667)) + +### Bug Fixes + +* fix broken javadoc by switching to dokka. ([4b76baf](https://github.com/googleapis/java-genai/commit/4b76baf1c1f6f8d802169fc138b90098c416bf42)) +* internal workflow change ([b80b142](https://github.com/googleapis/java-genai/commit/b80b1425359952ad1db25a3b5e5606cf5e6c6b5e)) + +## [1.49.0](https://github.com/googleapis/java-genai/compare/v1.48.0...v1.49.0) (2026-04-14) + + +### Bug Fixes + +* fix broken javadoc by switching to dokka. ([4b76baf](https://github.com/googleapis/java-genai/commit/4b76baf1c1f6f8d802169fc138b90098c416bf42)) +* internal workflow change ([b80b142](https://github.com/googleapis/java-genai/commit/b80b1425359952ad1db25a3b5e5606cf5e6c6b5e)) + +## [1.48.0](https://github.com/googleapis/java-genai/compare/v1.47.0...v1.48.0) (2026-04-13) + + +### Features + +* [Experimental] Add interactions support. ([abc1ee4](https://github.com/googleapis/java-genai/commit/abc1ee4b47c1af5fe7da9f98ce64fe4c7e3fcec7)) +* Add "eu" as a supported service location for Vertex AI platform. ([78e1bc1](https://github.com/googleapis/java-genai/commit/78e1bc19d154ba5dad4e4986a9d6e7f8a6c585b8)) +* Add Live Avatar new fields ([8e8146a](https://github.com/googleapis/java-genai/commit/8e8146a3a8d6d37e8fe691a6f96e7fd2b055d988)) +* Add webhook_config to batches.create() and models.generate_videos() ([ac0e49e](https://github.com/googleapis/java-genai/commit/ac0e49e187ecbda2b58d10e60161b3ab6fd24667)) + +## [1.47.0](https://github.com/googleapis/java-genai/compare/v1.46.0...v1.47.0) (2026-04-08) + + +### Documentation + +* Remove deprecated product recontext model samples from docstrings ([6f73c4a](https://github.com/googleapis/java-genai/commit/6f73c4a996f5ccdc1f2b73000c849cadcdeb8a62)) + +## [1.46.0](https://github.com/googleapis/java-genai/compare/v1.45.0...v1.46.0) (2026-04-01) + + +### Bug Fixes + +* Fix service_tier enums. ([d4641e4](https://github.com/googleapis/java-genai/commit/d4641e422c4dff90fc6a62cdbbe3e0d634b64740)) + +## [1.45.0](https://github.com/googleapis/java-genai/compare/v1.44.0...v1.45.0) (2026-03-28) + + +### Features + +* Add consent_audio and voice_consent_signature and AsyncSession.setup_complete ([959c01b](https://github.com/googleapis/java-genai/commit/959c01bb6ea75d4a498a6781f52d8741f3bade94)) +* Add labels field to Veo configs ([86f235a](https://github.com/googleapis/java-genai/commit/86f235af5751234c433236b93c92dc1d05e479bc)) +* Add model_status to GenerateContentResponse (Gemini API only) ([6c35249](https://github.com/googleapis/java-genai/commit/6c352493d503fb98e7738af3ea88ad7556b19a10)) +* Add part_metadata in Part (Gemini API only) ([6c35249](https://github.com/googleapis/java-genai/commit/6c352493d503fb98e7738af3ea88ad7556b19a10)) +* Add service tier to GenerateContent. ([5f61a16](https://github.com/googleapis/java-genai/commit/5f61a168d697588c2878461976cb31912cee9b3c)) +* **genai:** add TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO to TurnCoverage ([dbc4c33](https://github.com/googleapis/java-genai/commit/dbc4c33887d8d66cca0e474fde5faa8e98e13802)) +* support hyperparameters in distillation tuning ([fdedc74](https://github.com/googleapis/java-genai/commit/fdedc744dc3d447e94859c59379748286066353c)) +* Support rendered_parts in GroundingSupport ([6c35249](https://github.com/googleapis/java-genai/commit/6c352493d503fb98e7738af3ea88ad7556b19a10)) + + +### Bug Fixes + +* support us region routing ([3296bfe](https://github.com/googleapis/java-genai/commit/3296bfe392dc685a499a3c1c8477b23674089d77)) + +## [1.44.0](https://github.com/googleapis/java-genai/compare/v1.43.0...v1.44.0) (2026-03-18) + + +### Features + +* Support include_server_side_tool_invocations for genai. ([d92fdb1](https://github.com/googleapis/java-genai/commit/d92fdb167b1c06ae0dc3cbe8ad0c4c903a29f2ee)) + +## [1.43.0](https://github.com/googleapis/java-genai/compare/v1.42.0...v1.43.0) (2026-03-12) + + +### Features + +* Add inference_generation_config to EvaluationConfig for Tuning ([c9632f0](https://github.com/googleapis/java-genai/commit/c9632f024d80f0ede17b6a4df423c33cd09c6fa9)) +* Allow custom endpoints for authentication with Vertex AI in Java ([5b38728](https://github.com/googleapis/java-genai/commit/5b3872897a68d00f536b94bb11bb580c45e8cd55)) +* enable language code for audio transcription config in Live API for Vertex AI ([fb034ff](https://github.com/googleapis/java-genai/commit/fb034ff044d3c73721f3253845ac5e2c00e8d262)) + +## [1.42.0](https://github.com/googleapis/java-genai/compare/v1.41.0...v1.42.0) (2026-03-04) + + +### Features + +* Update data types from discovery doc. ([850d527](https://github.com/googleapis/java-genai/commit/850d527dd945a040c2aa9a50f82060c53fde4d64)) + + +### Bug Fixes + +* initialize comprehensive and curated history in constructor ([f74a426](https://github.com/googleapis/java-genai/commit/f74a426adcf282f726a49b38958c4df3982a2d0d)) + +## [1.41.0](https://github.com/googleapis/java-genai/compare/v1.40.0...v1.41.0) (2026-02-26) + + +### Features + +* Add Image Grounding support to GoogleSearch tool ([0daefbc](https://github.com/googleapis/java-genai/commit/0daefbc3ea09a341162ff95b68bf7f2e25fa41ea)) +* enable server side MCP and disable all other AFC when server side MCP is configured. ([498a2c4](https://github.com/googleapis/java-genai/commit/498a2c422dabb493d9b3b133b88156e5b44abae0)) +* examples ([917aee0](https://github.com/googleapis/java-genai/commit/917aee09737fec695fdb4fb665e6aaebfcf0a2fc)) +* initial integration ([917aee0](https://github.com/googleapis/java-genai/commit/917aee09737fec695fdb4fb665e6aaebfcf0a2fc)) +* set up pom + fix test ([917aee0](https://github.com/googleapis/java-genai/commit/917aee09737fec695fdb4fb665e6aaebfcf0a2fc)) + + +### Bug Fixes + +* use `NonClosingDelegatingHttpClient` ([917aee0](https://github.com/googleapis/java-genai/commit/917aee09737fec695fdb4fb665e6aaebfcf0a2fc)) + + +### Documentation + +* explain how to run tests ([4f6a811](https://github.com/googleapis/java-genai/commit/4f6a8112e8513bed34a5d35a16f21459006944c3)) + +## [1.40.0](https://github.com/googleapis/java-genai/compare/v1.39.0...v1.40.0) (2026-02-19) + + +### Features + +* Add `registerFiles` for Java. ([ce0b638](https://github.com/googleapis/java-genai/commit/ce0b6389330762ba649d25fc40d52b926232e7d1)) +* Add UnifiedMetric support to Vertex Tuning evaluation config ([a28ebfc](https://github.com/googleapis/java-genai/commit/a28ebfc3ddff73b9c998015a0d6d78bb6171b2aa)) +* Support multimodal embedding for Gemini Embedding 2.0 and support MaaS models in Models.embed_content() (Vertex AI API) ([23a7913](https://github.com/googleapis/java-genai/commit/23a7913309416b09e4d8fb39d704b5dc26aa22f1)) + +## [1.39.0](https://github.com/googleapis/java-genai/compare/v1.38.0...v1.39.0) (2026-02-07) + + +### Features + +* Support encryption_spec in tuning job creation configuration for GenAI SDK ([7a4fb51](https://github.com/googleapis/java-genai/commit/7a4fb51127dd9cba8e32587866ae03608505b2bd)) + +## [1.38.0](https://github.com/googleapis/java-genai/compare/v1.37.0...v1.38.0) (2026-02-05) + + +### Features + + +### Bug Fixes + +* 'No SLF4J providers were found' on examples ([97fa11f](https://github.com/googleapis/java-genai/commit/97fa11f7166b88b5d85dd6450ba345af7310b975)) +* Make Apache HTTP Components an optional Maven dependency in GenAI. ([a01e464](https://github.com/googleapis/java-genai/commit/a01e464573d0e7eea093734fcaad2d824173b41c)) +* Replace System .err & .out with correct (JUL) Logging in GenAI AsyncLive. ([1f756d6](https://github.com/googleapis/java-genai/commit/1f756d6a52b600f33793f898f30dd5cadaa52d23)) + +## [1.37.0](https://github.com/googleapis/java-genai/compare/v1.36.0...v1.37.0) (2026-01-30) + + +### Features + +* Support distillation tuning ([cec1b88](https://github.com/googleapis/java-genai/commit/cec1b88ab5a8d5cb801f4db19ce73f3f01732c70)) +* Support OSS Tuning in GenAI SDK ([868d8ed](https://github.com/googleapis/java-genai/commit/868d8edee6a449937ed8b74f909071d8496fc68f)) + + +### Bug Fixes + +* Add metadata in batch inlined response ([c80dd07](https://github.com/googleapis/java-genai/commit/c80dd070d9f23ec6463e7e704f003ffb4dba354c)) + +## [1.36.0](https://github.com/googleapis/java-genai/compare/v1.35.0...v1.36.0) (2026-01-22) + + +### Features + +* Add ModelArmorConfig support for prompt and response sanitization via the Model Armor service ([9c77a8f](https://github.com/googleapis/java-genai/commit/9c77a8f05959b205e025c70eb794740ac2e1724b)) + +## [1.35.0](https://github.com/googleapis/java-genai/compare/v1.34.0...v1.35.0) (2026-01-14) + + +### Features + +* voice activity support ([5ffcf2b](https://github.com/googleapis/java-genai/commit/5ffcf2b20c95bf7cd84070700383b105e849d7a3)) + +## [1.34.0](https://github.com/googleapis/java-genai/compare/v1.33.0...v1.34.0) (2026-01-08) + + +### Features + +* Add gemini-3-pro-preview support for local tokenizer ([40480f4](https://github.com/googleapis/java-genai/commit/40480f4e784f076be787c0c3213918e88ffc4296)) + + +### Documentation + +* Update Virtual Try-On model id in samples and docstrings ([e349635](https://github.com/googleapis/java-genai/commit/e349635621abe4b27a88a30e2f7c1ad960851767)) + +## [1.33.0](https://github.com/googleapis/java-genai/compare/v1.32.0...v1.33.0) (2026-01-07) + +**Note:** The artifacts for this version were not published to Maven. Please upgrade directly to version **1.34.0**. + +## [1.32.0](https://github.com/googleapis/java-genai/compare/v1.31.0...v1.32.0) (2025-12-17) + + +### Features + +* Add minimal and medium thinking levels. ([ecfadfe](https://github.com/googleapis/java-genai/commit/ecfadfe6717870d1ea403091863d16cec5fcff79)) +* Add PersonGeneration to ImageConfig for Vertex Gempix ([d8a4c43](https://github.com/googleapis/java-genai/commit/d8a4c432e5024bd171cf4b791925a40b285d7793)) +* Add ultra high resolution to the media resolution in Parts. ([7c9b7f6](https://github.com/googleapis/java-genai/commit/7c9b7f62275487183b7f5ded4db40af9a4422a67)) +* support multi speaker for Vertex AI ([c50e47b](https://github.com/googleapis/java-genai/commit/c50e47bfba44d7bd979b37b7c4b024424c08c29a)) + +## [1.31.0](https://github.com/googleapis/java-genai/compare/v1.30.0...v1.31.0) (2025-12-11) + + +### Features + +* Add enableEnhancedCivicAnswers feature in GenerateContentConfig ([0570478](https://github.com/googleapis/java-genai/commit/05704781fa7627efb5f4486b0a8763698bd6e6f2)) +* Add IMAGE_RECITATION and IMAGE_OTHER enum values to FinishReason ([26c3c35](https://github.com/googleapis/java-genai/commit/26c3c351fde231c943a3695af35961535923c8b1)) +* Add voice activity detection signal. ([d1ca685](https://github.com/googleapis/java-genai/commit/d1ca6854006248e1eab10212d1b1dade56e9b158)) + + +### Documentation + +* Add an example for ClientOptions usage ([0a8a26e](https://github.com/googleapis/java-genai/commit/0a8a26e0e75e791c2a99b012aba5c9bc09430cd7)) + +## [1.30.0](https://github.com/googleapis/java-genai/compare/v1.29.0...v1.30.0) (2025-12-08) + + +### Features + +* Add ProxyOptions in ClientOptions for configuring proxies ([eafdf79](https://github.com/googleapis/java-genai/commit/eafdf791f9beea50b6944a8f2118e9a1934f3a17)) +* Ephemeral token for Gemini Live API support in Java ([4ce094b](https://github.com/googleapis/java-genai/commit/4ce094b015e39574976086fb5c84a468481794b8)) +* Support ReplicatedVoiceConfig ([dbe314d](https://github.com/googleapis/java-genai/commit/dbe314de08a2a9b60f72ca4e67464a6f704c1ccb)) + +## [1.29.0](https://github.com/googleapis/java-genai/compare/v1.28.0...v1.29.0) (2025-12-03) + + +### Features + +* Add empty response for tunings.cancel() ([57218f5](https://github.com/googleapis/java-genai/commit/57218f56512ac6221a72f930d95a07dac2209cf6)) + + +### Bug Fixes + +* Match the versions of the Java Protobuf and Google API Common dependencies (com.google.protobuf:protobuf-java:3.25.5 & com.google.api:api-common:2.45.0) with Google Cloud Java SDKs. ([6c37f58](https://github.com/googleapis/java-genai/commit/6c37f5858f81f4bfd338c92c712d45222670e24b)) + + +### Documentation + +* Recommend using response_json_schema in error messages and docstrings. ([6b952e9](https://github.com/googleapis/java-genai/commit/6b952e949d46ae9d2123045a8dd741305c50a2ce)) + +## [1.28.0](https://github.com/googleapis/java-genai/compare/v1.27.0...v1.28.0) (2025-11-17) + + +### Features + +* add display name to FunctionResponseBlob ([8db8c57](https://github.com/googleapis/java-genai/commit/8db8c576247813991110e6ea10df999b756771ae)) +* add display name to FunctionResponseFileData ([f5ee8b7](https://github.com/googleapis/java-genai/commit/f5ee8b7744d7a729ac83c9072882c52345841625)) +* Add generate_content_config.thinking_level ([a47df92](https://github.com/googleapis/java-genai/commit/a47df920d935ba6e8e9751c0a50c0a2bb36c4189)) +* Add image output options to ImageConfig for Vertex ([3eac0b8](https://github.com/googleapis/java-genai/commit/3eac0b87c4e45e99123d7e321eb7d77007367b19)) +* Add part.media_resolution ([a47df92](https://github.com/googleapis/java-genai/commit/a47df920d935ba6e8e9751c0a50c0a2bb36c4189)) +* support Function call argument streaming for all languages ([f310452](https://github.com/googleapis/java-genai/commit/f3104521fc0cc934c2f5e29dedd8e22970a99897)) +* support upload to file search stores ([7862ce3](https://github.com/googleapis/java-genai/commit/7862ce38e950e3e6ff269e4f571474c42f4b19e4)) + +## [1.27.0](https://github.com/googleapis/java-genai/compare/v1.26.0...v1.27.0) (2025-11-12) + + +### Features + +* Add `images()` convenience method to `GenerateImagesResponse` ([155df8d](https://github.com/googleapis/java-genai/commit/155df8d25bdbcf1e6ef4b9859b5be28dfe9f943e)) +* Add EvaluationConfig support to tune() in Java ([795cf73](https://github.com/googleapis/java-genai/commit/795cf73d87894243d06c793262bed9b488167f95)) +* Automatically set response type in FunctionDeclaration during the AFC ([5ce99df](https://github.com/googleapis/java-genai/commit/5ce99df9136b1606fed3f385ff68b4ef84e931eb)) +* Support overriding the max read length in the JSON parser ([29d2fca](https://github.com/googleapis/java-genai/commit/29d2fcac0202bd8ba81c0973f172432b18bc3f79)) + + +### Bug Fixes + +* Add missing fields to the model types ([7b7b41f](https://github.com/googleapis/java-genai/commit/7b7b41f05b21a37c4ce9bd712a28d9432d07105f)) +* Fix base_steps parameter for recontext_image ([85aaa79](https://github.com/googleapis/java-genai/commit/85aaa79121489181879f1e0ad84d683c1d000f53)) +* Fix models.list() filter parameter ([123ada5](https://github.com/googleapis/java-genai/commit/123ada51cba5de22ec755716e551f398a6210a38)) + + +### Documentation + +* Add README for Files API ([6d206aa](https://github.com/googleapis/java-genai/commit/6d206aaf3f85cf1460418ddabcd1b6cd07693357)) + +## [1.26.0](https://github.com/googleapis/java-genai/compare/v1.25.0...v1.26.0) (2025-11-05) + + +### Features + +* Add clearXxx methods to data type builders ([a4900c9](https://github.com/googleapis/java-genai/commit/a4900c97ec7c256b45b729ae68404aea4fbf5830)) +* add complete stats to BatchJob ([659c65c](https://github.com/googleapis/java-genai/commit/659c65cc777c35ae5dc8ef84caf00f4aa30bb3db)) +* Add FileSearch tool and associated FileSearchStore management APIs ([8ada6ef](https://github.com/googleapis/java-genai/commit/8ada6efb0c2b2a2231acc08c952e2fc76e20a29d)) +* Add image_size to ImageConfig (Early Access Program) ([c1af981](https://github.com/googleapis/java-genai/commit/c1af981dc19fad22db68126ec6153d9fa20ec734)) +* Added phish filtering feature. ([ed4e12c](https://github.com/googleapis/java-genai/commit/ed4e12c44e9fec3c2131a52d995cb0602dc246a0)) +* Return response headers for generateContentStream ([82a8118](https://github.com/googleapis/java-genai/commit/82a8118968bb5da37ec81dce83580bd86767bf62)) +* Support lists as function parameters in AFC (fixes [#527](https://github.com/googleapis/java-genai/issues/527)) ([452d2e5](https://github.com/googleapis/java-genai/commit/452d2e50a6c13ab94d5de380d32dcb164379a2cb)) + + +### Bug Fixes + +* disable AFC when there are AFC incompatible tool presented. ([6099d87](https://github.com/googleapis/java-genai/commit/6099d871ff703606dffbf533a231869725f32bc6)) + + +### Documentation + +* add blank line before version update marker ([82616c2](https://github.com/googleapis/java-genai/commit/82616c23be6cf7295049026985d105c5c2993c7a)) +* Update Java SDK README spacing ([82616c2](https://github.com/googleapis/java-genai/commit/82616c23be6cf7295049026985d105c5c2993c7a)) + +## [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) + + +### Features + +* Add image_size field for Vertex Imagen 4 generation ([950c0c6](https://github.com/googleapis/java-genai/commit/950c0c657f786039e3a301bf1237a57ae324ff62)) +* Support API keys for VertexAI mode for Java SDK ([826c0dc](https://github.com/googleapis/java-genai/commit/826c0dca02e06fcb6c7980259b23e955db176ec6)) +* Support http headers in GenerateContentResponse ([5282774](https://github.com/googleapis/java-genai/commit/528277406279d772c01ac2a48544962408ac235b)) + + +### Bug Fixes + +* Defer loading ADC when credentials is provided explicitly in Live API ([a540614](https://github.com/googleapis/java-genai/commit/a5406140aeaf9774265a5bcce79dae0707ed9287)) +* **live:** Enhance security by moving api key from query parameters to header ([e48c7f1](https://github.com/googleapis/java-genai/commit/e48c7f1e73dadf5c5198f9b58cea322deb7a4ed0)) +* Pager throws an exception if list request returns nothing(correct behavior is returning a Pager without any items in it) ([0a2301b](https://github.com/googleapis/java-genai/commit/0a2301b19fcd3e4d3694d42780da8f5ffe5f9207)) + + +### Documentation + +* Update README with latest features in Client ([dcf70cc](https://github.com/googleapis/java-genai/commit/dcf70cc64a93355cdc6a2eedf172399dd332750e)) + +## [1.9.0](https://github.com/googleapis/java-genai/compare/v1.8.0...v1.9.0) (2025-07-16) + + +### Features + +* Add `addWatermark` parameter to the edit image configuration. ([c4598da](https://github.com/googleapis/java-genai/commit/c4598da0903d5dacb0c7bb4462aec1226ba259bf)) +* add Tuning support for Java ([0ab209d](https://github.com/googleapis/java-genai/commit/0ab209db99bf98b58f7273fb12843984c42cb910)) + + +### Documentation + +* Update generated video resolution config docstring ([9a2ced8](https://github.com/googleapis/java-genai/commit/9a2ced8ed3a1896b8170cc9ca117b61cb9eea705)) + +## [1.8.0](https://github.com/googleapis/java-genai/compare/v1.7.0...v1.8.0) (2025-07-09) + + +### Features + +* Add new languages for Imagen 4 prompt language ([7e1e6d2](https://github.com/googleapis/java-genai/commit/7e1e6d2ead45c7a0737e4a010fce266fb436d2dd)) + +## [1.7.0](https://github.com/googleapis/java-genai/compare/v1.6.0...v1.7.0) (2025-07-01) + + +### Features + +* Support Batches delete ([782465d](https://github.com/googleapis/java-genai/commit/782465d9c85c3637586fef490983771c4b4b5df0)) +* Support different media input in Vertex Live API ([7f4c6bf](https://github.com/googleapis/java-genai/commit/7f4c6bf58804764d568bd3412086ead75a388df0)) + + +### Bug Fixes + +* Remove default timeout ([d1f6201](https://github.com/googleapis/java-genai/commit/d1f6201892de9f37b913044dd494c68b81bcc13a)) + +## [1.6.0](https://github.com/googleapis/java-genai/compare/v1.5.0...v1.6.0) (2025-06-25) + + +### Features + +* Add compressionQuality enum for generate_videos ([b0e665b](https://github.com/googleapis/java-genai/commit/b0e665bf6ae09dc2146e49714a4855443a270776)) +* Add enhance_input_image and image_preservation_factor fields for upscale_image ([94a329a](https://github.com/googleapis/java-genai/commit/94a329abcd3c668065abfae511b55766ed051668)) +* allow users to access headers for generateContent method and generateContentStream ([0315357](https://github.com/googleapis/java-genai/commit/03153578ea64f0c34836ac62395aa867f44eac07)) +* Batches support in Java ([5ce13e9](https://github.com/googleapis/java-genai/commit/5ce13e9c79c4791d405b1dfa71c1d9358dc5a08d)) +* configure release-please to automatically update package version across all files during releases. ([9131ac2](https://github.com/googleapis/java-genai/commit/9131ac24fde477afb25deb516c7ace51530ed8d9)) +* expose the responseJsonSchema in GenerateContentConfig ([9d9acdb](https://github.com/googleapis/java-genai/commit/9d9acdb494358155cbb3c2ce3acbe55209bbdb7e)) +* support client.caches.update method ([345c2b9](https://github.com/googleapis/java-genai/commit/345c2b93789913d6d84cdde9c30f86ec4041bd24)) + + +### Documentation + +* add more comments to make it easier to follow live api code, and to explain the usage of new concepts like thenCompose. ([96c792c](https://github.com/googleapis/java-genai/commit/96c792c3aa84f632e0b46bb986de403ecbf4edc1)) +* improve generate images documentation ([44c21dd](https://github.com/googleapis/java-genai/commit/44c21dd78e0d0be0e681e991b15d3dae3be360f2)) +* Update description of thinking_budget. ([265f20a](https://github.com/googleapis/java-genai/commit/265f20addd9e9e76c249e6042d653c8cec9f27a4)) + +## [1.5.0](https://github.com/googleapis/java-genai/compare/v1.4.1...v1.5.0) (2025-06-19) + + +### Features + +* Add a default 5 minutes timeout to the Java SDK. ([d80d23b](https://github.com/googleapis/java-genai/commit/d80d23b7a8cb440410f9dd9556ee1259352285ef)) +* enable json schema for controlled output and function declaration. ([35d93d8](https://github.com/googleapis/java-genai/commit/35d93d84a349cf1032d2cc61bf4e3128386759d6)) +* Parametrize model ID in Java genai samples and set hardcoded model IDs as default values if model ID not passed in by user. ([c1b0948](https://github.com/googleapis/java-genai/commit/c1b0948af51bc746cbf350e4b6a60b6199d3ffe2)) +* resolve deep conditional nesting in Live API examples for better readability. ([aa71865](https://github.com/googleapis/java-genai/commit/aa718657f53f4bd9132a9b00816e7f5581108dec)) + + +### Documentation + +* fix small typo in comments ([a6bfe36](https://github.com/googleapis/java-genai/commit/a6bfe36843bed1575a03c86a092a17b35e48fd9f)) + +## [1.4.1](https://github.com/googleapis/java-genai/compare/v1.4.0...v1.4.1) (2025-06-12) + + +### Bug Fixes + +* Add backwards compatibility for generateVideos in Java SDK ([504984a](https://github.com/googleapis/java-genai/commit/504984ad8bc30636e47a6838d89fe097766e9484)) + + +### Miscellaneous Chores + +* release 1.4.1 ([49a57d8](https://github.com/googleapis/java-genai/commit/49a57d878379729a14ccd4846af67c67bbaf2419)) + +## [1.4.0](https://github.com/googleapis/java-genai/compare/v1.3.0...v1.4.0) (2025-06-11) + + +### Features + +* Add datastore_spec field for VertexAISearch ([8c8b47a](https://github.com/googleapis/java-genai/commit/8c8b47a79cbf9014325aeeab156f99db6181a265)) +* Add support for Veo frame interpolation and video extension ([94f5e41](https://github.com/googleapis/java-genai/commit/94f5e41da83de8caa24c27b32d430f8ea5e6d0d8)) +* RAG - Introducing context storing for Gemini Live API. ([d63d625](https://github.com/googleapis/java-genai/commit/d63d62583f554aca88062dfbf3c77cc65da812dd)) +* Support maxConnections and maxConnectionsPerHost in Client instantiation ([7a4a8ac](https://github.com/googleapis/java-genai/commit/7a4a8ac093adba2f0fb7b2558b41274da450010c)) +* Support passing builder classes to setter methods ([996c994](https://github.com/googleapis/java-genai/commit/996c994d6a2697b8b79dd48a7460eed49a408884)) +* Support passing builder varargs to setter methods ([0b08524](https://github.com/googleapis/java-genai/commit/0b08524b002b656c9c8a7a7f667a9efabb69dcfb)) +* Support varargs in Enum setter methods ([cd63fd0](https://github.com/googleapis/java-genai/commit/cd63fd0bdb124d8d2bebabc68f29a504ae1f3e7e)) +* Support varargs in setter methods ([0b08524](https://github.com/googleapis/java-genai/commit/0b08524b002b656c9c8a7a7f667a9efabb69dcfb)) + + +### Documentation + +* Add javadoc for setter methods in types classes ([996c994](https://github.com/googleapis/java-genai/commit/996c994d6a2697b8b79dd48a7460eed49a408884)) + ## [1.3.0](https://github.com/googleapis/java-genai/compare/v1.2.0...v1.3.0) (2025-06-04) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3ad5fb65e0f..c5a26ec83a4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,20 @@ # Contributing -The Google Gen AI SDK will accept contributions in the future. \ No newline at end of file +The Google Gen AI SDK will accept contributions in the future. + +## Running tests + +```sh +mvn clean test -Dtest='**/*Test' -Djacoco.skip=true +``` + +## JDK version + +The tests may fail if you use the wrong JDK version. See the currently supported JDK versions in [.github/workflows/unit-tests.yml]. + +To run the tests with a specific JDK version, which you must have installed, set the `JAVA_HOME` environment variable. For example: + +```sh +# Run with JDK 21 +JAVA_HOME=$(/usr/libexec/java_home -v 21) mvn clean test -Dtest='**/*Test' -Djacoco.skip=true +``` diff --git a/GEMINI.md b/GEMINI.md new file mode 100644 index 00000000000..c2c2e40f9f2 --- /dev/null +++ b/GEMINI.md @@ -0,0 +1,83 @@ +--- +trigger: always_on +description: Read this file when working on the GenAI Java SDK +--- + +> [!IMPORTANT] When working in this directory, you must also read the +> generator's context file at `google3/google/cloud/aiplatform/sdk/GEMINI.md`. + +# Java SDK for Google GenAI + +This directory contains the Java SDK for the Google GenAI project. It is designed to provide a Java interface for interacting with Gemini models, supporting both the Gemini Developer API (MLDev) and Gemini Enterprise Agent Platform API (Vertex AI). + +## Project Overview + +The Java SDK is largely auto-generated based on API discovery documents. However, it also includes hand-written core infrastructure to support authentication, HTTP communication, and custom serialization needs. + +### Relationship to the Central Generator + +As described in `google3/google/cloud/aiplatform/sdk/GEMINI.md`, this SDK is produced by the central Python-based multi-language SDK generator located at `//google/cloud/aiplatform/sdk/generator`. +- Language-specific logic for Java is contained in `java_generator.py` and `java_datatypes.py` (in the generator directory). +- The generator produces data classes and API methods based on discovery docs and configuration. +- **Important**: The generator updates files in `src/private` from files in `src/main`. Do NOT edit files in `src/private` directly. + +## Architecture and Key Components + +### Hand-written Core Files + +The following files in `src/main/java/com/google/genai/` are hand-written and form the core infrastructure of the SDK: + +- **`Client.java`**: The main entry point for the SDK. It provides access to all services (Models, Chats, Files, etc.) in both synchronous and asynchronous modes. Handles initialization with API keys or credentials. +- **`ApiClient.java`**: An abstract base class for issuing HTTP requests. It handles request building, URL construction, header execution (including auth), and OkHttpClient configuration. +- **`HttpApiClient.java`**: The default concrete implementation of `ApiClient` that uses OkHttp to make real network calls. +- **`ApiResponse.java`**: A simple wrapper around the HTTP response, providing access to status code, headers, and body content. +- **`Common.java`**: Contains utility methods for setting and getting values by path in JSON objects, URL encoding, and other common tasks. +- **`JsonSerializable.java`**: Provides base functionality for JSON serialization and deserialization using Jackson. +- **`Transformers.java`**: Contains static methods to transform parameters and types to match API expectations (e.g., converting model names to resource paths). +- **`ResponseStream.java`**: Manages streaming responses, ensuring SSE compliance and detecting application-level errors. +- **`ReplayApiClient.java`**: A testing-specific implementation of `ApiClient` that reads responses from replay files instead of making network calls. +- **`ReplayApiResponse.java`**: Used with `ReplayApiClient` to represent mocked responses. +- **`Chat.java`, `AsyncChat.java`, `ChatBase.java`**: Manage multi-turn chat sessions and history. +- **`UploadClient.java`**: Handles resumable file uploads to the File API. +- **`GoogleCredentialsHttpClient.java`**: Handles authentication using Google Credentials (typically for Vertex AI). +- **`AfcUtil.java`**: Utilities for Auto-Function Calling. + +### Custom Serialization (`CustomDurationDeserializer`) + +To handle API response fields that return duration as a string with an 's' suffix (e.g., "3.5s"), the SDK uses a custom deserializer in `JsonSerializable.java`: `CustomDurationDeserializer`. +- This deserializer ensures that fields mapped to `java.time.Duration` in Java can be successfully decoded from JSON. +- It parses the numeric part and creates a `Duration` instance. +- `JsonSerializable` also includes a `CustomDurationSerializer` to output the same format when serializing. + +## Development and Testing + +### Running Tests + +The project uses Maven for building and testing. + +To run all unit tests, you must set the environment variable for replay tests: + +```bash +export GOOGLE_GENAI_REPLAYS_DIRECTORY="`blaze info workspace`/google/cloud/aiplatform/sdk/genai/replays" +mvn clean test +``` + +### Running Examples + +Examples are located in `examples/`. To run all examples (recommended before release): +```bash +./run_examples.sh +``` + +## Modifying the SDK + +- **For changes to generated code**: Do NOT edit the generated files directly in `src/private`. Modify the generator configuration or templates in `//google/cloud/aiplatform/sdk/` or modify files in `src/main` and then run the generator: + ```bash + google/cloud/aiplatform/sdk/generator/run_generator.sh --langs java + ``` +- **For changes to core infrastructure**: Modify the hand-written files in `src/main`. +- **Knowledge Sharing**: Every time you make a code change in this Java GenAI SDK, try to add useful knowledge into this `GEMINI.md` file if it is necessary or helpful for future maintainers (e.g., documenting new hand-written files, custom serialization patterns, or specific workflow gotchas). + +## Legacy Names + +- Similar to other SDKs, you might still find legacy names like "mldev" (representing Gemini API) or "vertex" (representing Gemini Enterprise Agent Platform API) in generator code and test files. diff --git a/README.md b/README.md index 4dd54a8b4d2..47233672678 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Google Gen AI Java SDK Java idiomatic SDK for the -[Gemini Developer APIs][gemini-api-doc] and [Vertex AI][vertex-api-doc] APIs. +[Gemini Developer APIs][gemini-api-doc] and [Gemini Enterprise Agent Platform][gemini-enterprise-agent-platform-doc] APIs. [![Maven][maven-version-image]][maven-version-link] [![Javadoc][javadoc-image]][javadoc-link] @@ -10,19 +10,17 @@ Java idiomatic SDK for the If you're using Maven, add the following to your dependencies: - - +[//]: # ({x-version-update-start:google-genai:released}) ```xml com.google.genai google-genai - 1.3.0 + 1.47.0 ``` - - +[//]: # ({x-version-update-end}) ## Getting Started @@ -45,6 +43,9 @@ Client client = Client.builder().apiKey("your-api-key").build(); ``` #### Instantiate a client that uses Vertex AI API + +##### Using project and location + ```java import com.google.genai.Client; @@ -57,39 +58,188 @@ Client client = Client.builder() .build(); ``` +##### Using API key on Vertex AI (GCP Express Mode) + +```java +import com.google.genai.Client; + +// Explicitly set the `apiKey` and `vertexAI(true)` to use Vertex AI backend +// in express mode. +Client client = Client.builder() + .apiKey("your-api-key") + .vertexAI(true) + .build(); +``` + #### (Optional) Using environment variables: You can create a client by configuring the necessary environment variables. Configuration setup instructions depends on whether you're using the Gemini Developer API or the Gemini API in Vertex AI. -**Gemini Developer API:** Set `GOOGLE_API_KEY` as shown below: +**Gemini Developer API:** Set the `GOOGLE_API_KEY`. It will automatically be +picked up by the client. Note that `GEMINI_API_KEY` is a legacy environment +variable, it's recommended to use `GOOGLE_API_KEY` only. But if both are set, +`GOOGLE_API_KEY` takes precedence. ```bash export GOOGLE_API_KEY='your-api-key' ``` **Gemini API on Vertex AI:** Set `GOOGLE_GENAI_USE_VERTEXAI`, -`GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, as shown below: +`GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, or `GOOGLE_API_KEY` for +Vertex AI express mode. It's recommended that you set only project & location, +or API key. But if both are set, project & location takes precedence. ```bash export GOOGLE_GENAI_USE_VERTEXAI=true + +// Set project and location for Vertex AI authentication export GOOGLE_CLOUD_PROJECT='your-project-id' export GOOGLE_CLOUD_LOCATION='us-central1' +// or API key for express mode +export GOOGLE_API_KEY='your-api-key' ``` +After configuring the environment variables, you can instantiate a client +without passing any variables. + ```java import com.google.genai.Client; Client client = new Client(); ``` +### API Selection + +By default, the SDK uses the beta API endpoints provided by Google to support +preview features in the APIs. The stable API endpoints can be selected by +setting the API version to `v1`. + +To set the API version use `HttpOptions`. For example, to set the API version to +`v1` for Vertex AI: + +```java +import com.google.genai.Client; +import com.google.genai.types.HttpOptions; + +Client client = Client.builder() + .project("your-project") + .location("your-location") + .vertexAI(true) + .httpOptions(HttpOptions.builder().apiVersion("v1")) + .build(); +``` + +To set the API version to `v1alpha` for the Gemini Developer API: + +```java +import com.google.genai.Client; +import com.google.genai.types.HttpOptions; + +Client client = Client.builder() + .apiKey("your-api-key") + .httpOptions(HttpOptions.builder().apiVersion("v1alpha")) + .build(); +``` + +### HttpOptions + +Besides `apiVersion`, [HttpOptions](https://github.com/googleapis/java-genai/blob/main/src/main/java/com/google/genai/types/HttpOptions.java) +also allows for flexible customization of HTTP request parameters such as +`baseUrl`, `headers`, and `timeout`: + +```java +HttpOptions httpOptions = HttpOptions.builder() + .baseUrl("your-own-endpoint.com") + .headers(ImmutableMap.of("key", "value")) + .timeout(600) + .build(); +``` + +Beyond client-level configuration, `HttpOptions` can also be set on a +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, including connection +pool settings and proxy configurations. + +#### Connection Pool +You can configure the connection pool via `maxConnections` (total maximum +connections) and `maxConnectionsPerHost` (maximum connections to a single host). + +```java +import com.google.genai.Client; +import com.google.genai.types.ClientOptions; + +Client client = + Client.builder() + .apiKey("your-api-key") + .clientOptions( + ClientOptions.builder().maxConnections(64).maxConnectionsPerHost(16).build()) + .build(); +``` + +#### Proxy +If your environment requires connecting through a proxy, you can configure it +using `ProxyOptions`. The SDK supports `HTTP`, `SOCKS`, and `DIRECT` (no proxy) +connection types, along with basic proxy authentication. + +```java +import com.google.genai.Client; +import com.google.genai.types.ClientOptions; +import com.google.genai.types.ProxyOptions; +import com.google.genai.types.ProxyType; + +ClientOptions clientOptions = + ClientOptions.builder() + .proxyOptions( + ProxyOptions.builder() + .type(ProxyType.Known.HTTP) + .host("your-proxy-host") + .port(8080) + .username("your-proxy-username") + .password("your-proxy-password")) + .build(); +Client client = Client.builder().apiKey("your-api-key").clientOptions(clientOptions).build(); +``` + +If `ProxyOptions` is provided with `type` set to `DIRECT`, it will enforce a +direct connection, bypassing any system-level proxy settings. + ### 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 @@ -106,10 +256,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))); } } ``` @@ -139,7 +296,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()); } @@ -188,20 +406,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); @@ -213,7 +431,7 @@ public class GenerateContentWithFunctionCall { } ``` -#### Stream Generated Content +##### Stream Generated Content To get a streamed response, you can use the `generateContentStream` method: ```java @@ -225,13 +443,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) { @@ -245,7 +461,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. @@ -258,12 +474,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( @@ -275,104 +490,489 @@ 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. +##### Generate Content with JSON response schema +To get a response in JSON by passing in a response schema to the +`GenerateContent` API. ```java package ; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; 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; +import com.google.genai.types.Schema; +import com.google.genai.types.Type; -public class GenerateContentWithConfigs { +public class GenerateContentWithSchema { 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(); - + // Define the schema for the response, in Json format. + ImmutableMap schema = ImmutableMap.of( + "type", "object", + "properties", ImmutableMap.of( + "recipe_name", ImmutableMap.of("type", "string"), + "ingredients", ImmutableMap.of( + "type", "array", + "items", ImmutableMap.of("type", "string") + ) + ), + "required", ImmutableList.of("recipe_name", "ingredients") + ); + + // Set the response schema in GenerateContentConfig GenerateContentConfig config = GenerateContentConfig.builder() + .responseMimeType("application/json") .candidateCount(1) - .maxOutputTokens(1024) - .safetySettings(safetySettings) - .systemInstruction(systemInstruction) - .tools(ImmutableList.of(googleSearchTool)) + .responseSchema(schema) .build(); GenerateContentResponse response = - client.models.generateContent("gemini-2.0-flash-001", "Tell me the history of LLM", config); + client.models.generateContent("gemini-2.5-flash", "Tell me your name", config); System.out.println("Response: " + response.text()); } } ``` -#### Generate Content with JSON response schema -To get a response in JSON by passing in a response schema to the -`GenerateContent` API. +#### 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.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.Schema; -import com.google.genai.types.Type; +import com.google.genai.types.CountTokensResponse; -public class GenerateContentWithSchema { +public class CountTokens { public static void main(String[] args) { Client client = new Client(); - Schema schema = - Schema.builder() - .type("object") - .properties( - ImmutableMap.of( - "name", Schema.builder().type(Type.Known.STRING).description("Your Name").build())) + 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, as well as multimodal content like images or videos via Vertex AI. + +```java +package ; + +import com.google.genai.Client; +import com.google.genai.types.EmbedContentConfig; +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); + + // Multimodal embedding with Vertex AI + Client vertexClient = Client.builder().vertexAI(true).build(); + EmbedContentConfig config = + EmbedContentConfig.builder() + .outputDimensionality(10) + .title("test_title") + .taskType("RETRIEVAL_DOCUMENT") .build(); - GenerateContentConfig config = - GenerateContentConfig.builder() - .responseMimeType("application/json") - .candidateCount(1) - .responseSchema(schema) + + EmbedContentResponse mmResponse = + vertexClient.models.embedContent( + "gemini-embedding-2-exp-11-2025", + Content.fromParts( + Part.fromText("Hello"), + Part.fromUri("gs://cloud-samples-data/generative-ai/image/a-man-and-a-dog.png", "image/png")), + config); + System.out.println("Multimodal embedding response: " + mmResponse); + } +} +``` + +### 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(); - GenerateContentResponse response = - client.models.generateContent("gemini-2.0-flash-001", "Tell me your name", config); + GenerateImagesResponse response = + client.models.generateImages( + "imagen-3.0-generate-002", "Robot holding a red skateboard", config); - System.out.println("Response: " + response.text()); + if (generatedImagesResponse.images().isEmpty()) { + System.out.println("Unable to generate images."); + } + System.out.println("Generated " + generatedImagesResponse.images().size() + " images."); + Image generatedImage = generatedImagesResponse.images().get(0); } } ``` +#### 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 + } + ); + } + ); + } +} +``` + +### Files API + +Gemini models support various input data types, including text, images, and +audio. The Files API allows you to upload and manage these media files for use +with Gemini models. **This feature is exclusively supported by the Gemini API**. + +#### Usage info +You can use the Files API to upload and interact with media files. The Files API +lets you store up to 20 GB of files per project, with a per-file maximum size of +2 GB. Files are stored for 48 hours. During that time, you can use the API to +get metadata about the files, but you can't download the files. The Files API is +available at no cost in all regions where the Gemini API is available. + +The basic operations are: + +1. **Upload**: You can use the Files API to upload a media file. Always use +the Files API when the total request size (including the files, text prompt, +system instructions, etc.) is larger than 20 MB. + +2. **Get**: You can verify that the API successfully stored the uploaded file +and get its metadata. + +3. **List**: You can upload multiple files using the Files API. The following +code gets a list of all the files uploaded. + +4. **Delete**: Files are automatically deleted after 48 hours. You can also +manually delete an uploaded file: + +#### Sample usage + +```java +package ; + +import com.google.genai.Client; +import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.Content; +import com.google.genai.types.DeleteFileResponse; +import com.google.genai.types.File; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.ListFilesConfig; +import com.google.genai.types.Part; +import com.google.genai.types.UploadFileConfig; + +/** An example of how to use the Files module to upload, retrieve, list, and delete files. */ +public final class FileOperations { + public static void main(String[] args) { + Client client = new Client(); + + // Upload a file to the API. + try { + File file = + client.files.upload( + "path/to/your/file.pdf", + UploadFileConfig.builder().mimeType("application/pdf").build()); + + // Use the uploaded file in the generateContent + Content content = + Content.fromParts( + Part.fromText("Summary this pdf."), + Part.fromUri(file.name().get(), file.mimeType().get())); + GenerateContentResponse response = + client.models.generateContent("gemini-2.5-flash", content, null); + + // Get the uploaded file. + File retrievedFile = client.files.get(file.name().get(), null); + + // List all files. + System.out.println("List files: "); + for (File f : client.files.list(ListFilesConfig.builder().pageSize(10).build())) { + System.out.println("File name: " + f.name().get()); + } + + // Delete the uploaded file. + client.files.delete(file.name().get(), null); + + } catch (GenAiIOException e) { + System.out.println("An error occurred while uploading the file: " + e.getMessage()); + } + } +} +``` + + ## Versioning This library follows [Semantic Versioning](http://semver.org/). diff --git a/examples/pom.xml b/examples/pom.xml index 57d2a56ccb5..18b400fef78 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -5,17 +5,18 @@ com.google.genai.examples google-genai-examples - 1.4.0-SNAPSHOT + 1.54.0-SNAPSHOT google-genai-examples UTF-8 1.8 1.8 - 1.4.0-SNAPSHOT + + 1.54.0-SNAPSHOT + - org.apache.maven.plugins @@ -27,8 +28,39 @@ + + org.codehaus.mojo + exec-maven-plugin + 3.5.0 + + false + + + + org.graalvm.buildtools + native-maven-plugin + 0.11.1 + true + + + + build + test + + package + + + + + -Ob + --no-fallback + --verbose + + com.google.genai.examples.GenerateContent + genai-example-app + + - @@ -37,5 +69,15 @@ google-genai ${google-genai.version} + + org.slf4j + jul-to-slf4j + 2.0.17 + + + org.slf4j + slf4j-simple + 2.0.17 + 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 new file mode 100644 index 00000000000..f200a1ee6d6 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/BatchManagement.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. + */ + +/** + * 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.BatchManagement" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.BatchJob; +import com.google.genai.types.BatchJobDestination; +import com.google.genai.types.BatchJobSource; +import com.google.genai.types.Content; +import com.google.genai.types.CreateBatchJobConfig; +import com.google.genai.types.InlinedRequest; +import com.google.genai.types.ListBatchJobsConfig; +import com.google.genai.types.Part; + +/** An example of using the Unified Gen AI Java SDK to do operations on batch jobs. */ +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 + // 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"); + // Create a batch job. + BatchJobSource batchJobSource = + BatchJobSource.builder() + .gcsUri("gs://unified-genai-tests/batches/input/generate_content_requests.jsonl") + .format("jsonl") + .build(); + CreateBatchJobConfig config = + CreateBatchJobConfig.builder() + .displayName("summarize the pdf") + .dest( + BatchJobDestination.builder() + .gcsUri("gs://unified-genai-tests/batches/output") + .format("jsonl")) + .build(); + BatchJob batchJob1 = client.batches.create(modelId, batchJobSource, config); + System.out.println("Created batch job: " + batchJob1); + // Get the batch job by name. + BatchJob batchJob2 = client.batches.get(batchJob1.name().get(), null); + System.out.println("Get batch job: " + batchJob2); + // Cancel the batch job. + client.batches.cancel(batchJob1.name().get(), null); + System.out.println("Cancelled batch job: " + batchJob1.name().get()); + } else { + System.out.println("Using Gemini Developer API"); + // Create a batch job. + BatchJobSource batchJobSource = + BatchJobSource.builder() + .inlinedRequests( + InlinedRequest.builder() + .contents(Content.builder().parts(Part.fromText("Hello!")))) + .build(); + CreateBatchJobConfig config = + CreateBatchJobConfig.builder().displayName("test-batch-job-java").build(); + BatchJob batchJob1 = client.batches.create(modelId, batchJobSource, config); + System.out.println("Created batch job: " + batchJob1); + // Get the batch job by name. + BatchJob batchJob2 = client.batches.get(batchJob1.name().get(), null); + System.out.println("Get batch job: " + batchJob2); + // Cancel the batch job. + client.batches.cancel(batchJob1.name().get(), null); + System.out.println("Cancelled batch job: " + batchJob1.name().get()); + } + + // List all batch jobs. + System.out.println("List batch jobs resource names: "); + for (BatchJob b : + client.batches.list(ListBatchJobsConfig.builder().pageSize(5).build()).page()) { + System.out.println(b.name().get()); + System.out.println(b.state().get()); + } + + } + + private BatchManagement() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/BatchManagementAsync.java b/examples/src/main/java/com/google/genai/examples/BatchManagementAsync.java new file mode 100644 index 00000000000..df00b9b3d15 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/BatchManagementAsync.java @@ -0,0 +1,182 @@ +/* + * 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.BatchManagementAsync" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.AsyncPager; +import com.google.genai.Client; +import com.google.genai.types.BatchJob; +import com.google.genai.types.BatchJobDestination; +import com.google.genai.types.BatchJobSource; +import com.google.genai.types.Content; +import com.google.genai.types.CreateBatchJobConfig; +import com.google.genai.types.InlinedRequest; +import com.google.genai.types.ListBatchJobsConfig; +import com.google.genai.types.Part; +import java.util.concurrent.CompletableFuture; + +/** An example of using the Unified Gen AI Java SDK to do async operations on batch jobs. */ +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 + // 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"); + // Create a batch job. + BatchJobSource batchJobSource = + BatchJobSource.builder() + .bigqueryUri( + "bq://vertex-sdk-dev.unified_genai_tests_batches.generate_content_requests") + .format("bigquery") + .build(); + CreateBatchJobConfig config = + CreateBatchJobConfig.builder() + .displayName("test batch") + .dest( + BatchJobDestination.builder() + .bigqueryUri( + "bq://vertex-sdk-dev.unified_genai_tests_batches.generate_content_output") + .format("bigquery")) + .build(); + CompletableFuture finalFuture = + client + .async + .batches + .create(modelId, batchJobSource, config) + .thenCompose( + batchJob1 -> { + System.out.println("Created batch job: " + batchJob1.name()); + CompletableFuture batchJob2Future = + client.async.batches.get(batchJob1.name().get(), null); + + return batchJob2Future.thenCompose( + batchJob2 -> { + System.out.println("Get batch job: " + batchJob2.name()); + // Cancel the batch job. This is now nested, so it happens after get + // completes. + return client + .async + .batches + .cancel(batchJob1.name().get(), null) + .thenAccept( + cancelResponse -> { + System.out.println( + "Successfully initiated cancellation for batch job: " + + batchJob1.name()); + }); + }); + }); + finalFuture.join(); + System.out.println("All batch job operations completed."); + } else { + System.out.println("Using Gemini Developer API"); + // Create a batch job. + BatchJobSource batchJobSource = + BatchJobSource.builder() + .inlinedRequests( + InlinedRequest.builder() + .contents(Content.builder().parts(Part.fromText("Hello!")))) + .build(); + CreateBatchJobConfig config = + CreateBatchJobConfig.builder().displayName("test-batch-job-java").build(); + CompletableFuture finalFuture = + client + .async + .batches + .create(modelId, batchJobSource, config) + .thenCompose( + batchJob1 -> { + System.out.println("Created batch job: " + batchJob1.name()); + CompletableFuture batchJob2Future = + client.async.batches.get(batchJob1.name().get(), null); + + return batchJob2Future.thenCompose( + batchJob2 -> { + System.out.println("Get batch job: " + batchJob2.name()); + // Cancel the batch job. This is now nested, so it happens after get + // completes. + return client + .async + .batches + .cancel(batchJob1.name().get(), null) + .thenAccept( + cancelResponse -> { + System.out.println( + "Successfully initiated cancellation for batch job: " + + batchJob1.name()); + }); + }); + }); + finalFuture.join(); + System.out.println("All batch job operations completed."); + } + // List all batch jobs. + CompletableFuture> asyncPagerFuture = + client.async.batches.list(ListBatchJobsConfig.builder().pageSize(10).build()); + asyncPagerFuture + .thenCompose( + asyncPager -> { + System.out.println("List all batch job names: "); + return asyncPager.forEach( + item -> System.out.println("Batch job name: " + item.name().get())); + }) + .join(); + } + + private BatchManagementAsync() {} +} 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 3120b5ace83..ad37e1ffe31 100644 --- a/examples/src/main/java/com/google/genai/examples/CachedContentOperations.java +++ b/examples/src/main/java/com/google/genai/examples/CachedContentOperations.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.CachedContentOperations" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -48,6 +49,7 @@ import com.google.genai.types.DeleteCachedContentResponse; 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; @@ -60,6 +62,13 @@ public final class CachedContentOperations { 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 @@ -89,12 +98,18 @@ public static void main(String[] args) { .contents(content) .build(); - CachedContent cachedContent1 = client.caches.create("gemini-2.0-flash-001", config); + CachedContent cachedContent1 = client.caches.create(modelId, config); System.out.println("Created cached content: " + cachedContent1); // Get the cached content by name. CachedContent cachedContent2 = client.caches.get(cachedContent1.name().get(), null); - System.out.println("get cached content: " + cachedContent2); + System.out.println("Get cached content: " + cachedContent2); + + CachedContent cachedContent3 = + client.caches.update( + cachedContent1.name().get(), + UpdateCachedContentConfig.builder().ttl(Duration.ofMinutes(10)).build()); + System.out.println("Update cached content: " + cachedContent3); // List all cached contents. System.out.println("List cached contents resrouce names: "); 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 7db6a2c6a1b..62f16eda543 100644 --- a/examples/src/main/java/com/google/genai/examples/CachedContentOperationsAsync.java +++ b/examples/src/main/java/com/google/genai/examples/CachedContentOperationsAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.CachedContentOperationsAsync" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -65,6 +66,13 @@ public final class CachedContentOperationsAsync { 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 @@ -98,7 +106,7 @@ public static void main(String[] args) { contentFuture.thenCompose( content -> client.async.caches.create( - "gemini-2.0-flash-001", + modelId, CreateCachedContentConfig.builder() .systemInstruction(Content.fromParts(Part.fromText("summarize the pdf"))) .expireTime(Instant.now().plus(Duration.ofHours(1))) 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 c43b72897b4..618d6acb360 100644 --- a/examples/src/main/java/com/google/genai/examples/ChatWithFunctionCall.java +++ b/examples/src/main/java/com/google/genai/examples/ChatWithFunctionCall.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.ChatWithFunctionCall" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -59,6 +60,13 @@ public static Integer divideTwoIntegers(int numerator, int denominator) { } public static void main(String[] args) throws NoSuchMethodException { + 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 @@ -85,7 +93,7 @@ public static void main(String[] args) throws NoSuchMethodException { GenerateContentConfig.builder().tools(Tool.builder().functions(method1, method2)).build(); // Create a chat session. - Chat chatSession = client.chats.create("gemini-2.0-flash-001", config); + Chat chatSession = client.chats.create(modelId, config); GenerateContentResponse response1 = chatSession.sendMessage("what is the weather in San Francisco?"); 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 de3f94a0223..f79b0a38db6 100644 --- a/examples/src/main/java/com/google/genai/examples/ChatWithHistory.java +++ b/examples/src/main/java/com/google/genai/examples/ChatWithHistory.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.ChatWithHistory" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -48,6 +49,13 @@ /** 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) { + 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 @@ -65,7 +73,7 @@ public static void main(String[] args) { } // Create a chat session. - Chat chatSession = client.chats.create("gemini-2.0-flash-001"); + Chat chatSession = client.chats.create(modelId); GenerateContentResponse response = chatSession.sendMessage("Can you tell me a story about cheese in 100 words?"); 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 24901087bfa..24c5b17a71a 100644 --- a/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsync.java +++ b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.ChatWithHistoryAsync" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -49,6 +50,13 @@ /** 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) { + 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 @@ -66,7 +74,7 @@ public static void main(String[] args) { } // Create an async chat session. - AsyncChat chatSession = client.async.chats.create("gemini-2.0-flash-001"); + AsyncChat chatSession = client.async.chats.create(modelId); CompletableFuture chatResponseFuture = chatSession.sendMessage("Can you tell me a story about cheese in 100 words?"); 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 b974dd7ae37..427c3840b80 100644 --- a/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsyncStreaming.java +++ b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsyncStreaming.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.ChatWithHistoryAsyncStreaming" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -53,6 +54,13 @@ */ public final class ChatWithHistoryAsyncStreaming { 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 @@ -70,7 +78,7 @@ public static void main(String[] args) { } // Create an async chat session. - AsyncChat chatSession = client.async.chats.create("gemini-2.0-flash-001"); + AsyncChat chatSession = client.async.chats.create(modelId); CompletableFuture> chatResponseFuture = chatSession.sendMessageStream("Can you tell me a story about cheese in 100 words?"); diff --git a/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsyncStreamingFunctionCall.java b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsyncStreamingFunctionCall.java new file mode 100644 index 00000000000..489051775c6 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryAsyncStreamingFunctionCall.java @@ -0,0 +1,164 @@ +/* + * 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.ChatWithHistoryAsyncStreamingFunctionCall" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.common.collect.ImmutableMap; +import com.google.genai.AsyncChat; +import com.google.genai.Client; +import com.google.genai.ResponseStream; +import com.google.genai.types.Content; +import com.google.genai.types.FunctionCallingConfig; +import com.google.genai.types.FunctionResponse; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.Part; +import com.google.genai.types.Tool; +import com.google.genai.types.ToolConfig; +import java.lang.reflect.Method; +import java.util.concurrent.CompletableFuture; + +/** + * An example of using the Unified Gen AI Java SDK to create an async streaming chat session with + * history. + */ +public final class ChatWithHistoryAsyncStreamingFunctionCall { + /** A callable function to get the current weather. */ + public static String getCurrentWeather(String location) { + return "The weather in " + location + " is " + "very nice."; + } + + public static void main(String[] args) throws NoSuchMethodException { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_3_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 does not support streaming function calling."); + return; + } + + // Add the methods as callable functions to the tool. + Method method1 = + ChatWithHistoryAsyncStreamingFunctionCall.class.getDeclaredMethod( + "getCurrentWeather", String.class); + + GenerateContentConfig config = + GenerateContentConfig.builder() + .tools(Tool.builder().functions(method1)) + .toolConfig( + ToolConfig.builder() + .functionCallingConfig( + FunctionCallingConfig.builder().streamFunctionCallArguments(true))) + .build(); + + AsyncChat chatSession = client.async.chats.create(modelId, config); + + CompletableFuture> chatResponseFuture = + chatSession.sendMessageStream("what is the weather in San Francisco?", null); + + chatResponseFuture + .thenAccept( + responseStream -> { + System.out.println("Streaming response:"); + // Iterate over the stream and print each response as it arrives. + for (GenerateContentResponse response : responseStream) { + System.out.print(response.functionCalls()); + } + }) + .whenComplete( + (response, throwable) -> { + if (throwable != null) { + System.out.println("Chat response future failed: " + throwable.getMessage()); + } + }) + .join(); + + FunctionResponse functionResponse = + FunctionResponse.builder() + .name("getCurrentWeather") + .response(ImmutableMap.of("response", "The weather in San Francisco is very nice.")) + .build(); + + CompletableFuture> chatResponse2Future = + chatSession.sendMessageStream( + Content.builder() + .parts(Part.builder().functionResponse(functionResponse).build()) + .role("user") + .build()); + + chatResponse2Future + .thenAccept( + responseStream -> { + System.out.println("\n\nFinal Model Response:"); + for (GenerateContentResponse response : responseStream) { + if (response.text() != null) { + System.out.print(response.text()); + } + } + }) + .join(); + + // Get the history of the chat session. + // History is added after the stream is consumed and includes the aggregated response from the + // stream, so chatSession.getHistory(false) here returns 2 items (1 user-model message pair) + System.out.println("History: " + chatSession.getHistory(false)); + } + + private ChatWithHistoryAsyncStreamingFunctionCall() {} +} 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 b3bacb37e63..54b9be2f62f 100644 --- a/examples/src/main/java/com/google/genai/examples/ChatWithHistoryStreaming.java +++ b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryStreaming.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.ChatWithHistoryStreaming" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -51,6 +52,13 @@ */ public final class ChatWithHistoryStreaming { 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 @@ -68,7 +76,7 @@ public static void main(String[] args) { } // Create a chat session. - Chat chatSession = client.chats.create("gemini-2.0-flash-001"); + Chat chatSession = client.chats.create(modelId); ResponseStream responseStream = chatSession.sendMessageStream("Can you tell me a story about cheese in 100 words?", null); diff --git a/examples/src/main/java/com/google/genai/examples/ChatWithHistoryStreamingFunctionCall.java b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryStreamingFunctionCall.java new file mode 100644 index 00000000000..1f4d03acb4b --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/ChatWithHistoryStreamingFunctionCall.java @@ -0,0 +1,152 @@ +/* + * 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.ChatWithHistoryStreamingFunctionCall" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.common.collect.ImmutableMap; +import com.google.genai.Chat; +import com.google.genai.Client; +import com.google.genai.ResponseStream; +import com.google.genai.types.Content; +import com.google.genai.types.FunctionCallingConfig; +import com.google.genai.types.FunctionResponse; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.Part; +import com.google.genai.types.Tool; +import com.google.genai.types.ToolConfig; +import java.lang.reflect.Method; + +/** + * An example of using the Unified Gen AI Java SDK to create a chat session and stream the response. + */ +public final class ChatWithHistoryStreamingFunctionCall { + /** A callable function to get the current weather. */ + public static String getCurrentWeather(String location) { + return "The weather in " + location + " is " + "very nice."; + } + + public static void main(String[] args) throws NoSuchMethodException { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_3_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 does not support streaming function calling."); + return; + } + + // Add the methods as callable functions to the tool. + Method method1 = + ChatWithHistoryStreamingFunctionCall.class.getDeclaredMethod( + "getCurrentWeather", String.class); + + GenerateContentConfig config = + GenerateContentConfig.builder() + .tools(Tool.builder().functions(method1)) + .toolConfig( + ToolConfig.builder() + .functionCallingConfig( + FunctionCallingConfig.builder().streamFunctionCallArguments(true))) + .build(); + + // Create a chat session. + Chat chatSession = client.chats.create(modelId, config); + + ResponseStream responseStream = + chatSession.sendMessageStream("what is the weather in San Francisco?", null); + + System.out.println("Streaming response:"); + for (GenerateContentResponse response : responseStream) { + // Iterate over the stream and print each response as it arrives. + System.out.print(response.functionCalls()); + } + + FunctionResponse functionResponse = + FunctionResponse.builder() + .name("getCurrentWeather") + .response(ImmutableMap.of("response", "The weather in San Francisco is very nice.")) + .build(); + ResponseStream responseStream2 = + chatSession.sendMessageStream( + Content.builder() + .parts(Part.builder().functionResponse(functionResponse).build()) + .role("user") + .build(), + null); + System.out.println("Streaming response 2:"); + for (GenerateContentResponse response : responseStream2) { + // Iterate over the stream and print each response as it arrives. + System.out.print(response.text()); + } + + ResponseStream responseStream3 = + chatSession.sendMessageStream("Thanks!", null); + for (GenerateContentResponse response : responseStream3) { + // Iterate over the stream and print each response as it arrives. + System.out.print(response.text()); + } + + // Get the history of the chat session. + // History is added after the stream is consumed and includes the aggregated response from the + // stream, so chatSession.getHistory(false) here returns 4 items (2 user-model message pairs) + System.out.println("History: " + chatSession.getHistory(false)); + } + + private ChatWithHistoryStreamingFunctionCall() {} +} 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 2652394a06d..e819816b19e 100644 --- a/examples/src/main/java/com/google/genai/examples/ComputeTokens.java +++ b/examples/src/main/java/com/google/genai/examples/ComputeTokens.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.ComputeTokens" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -45,6 +46,13 @@ /** 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) { + 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 @@ -58,11 +66,12 @@ 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 = - client.models.computeTokens("gemini-2.0-flash-001", "What is your name?", null); + client.models.computeTokens(modelId, "What is your name?", null); System.out.println("Compute tokens response: " + 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..9bb51eb960e --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/Constants.java @@ -0,0 +1,67 @@ +/* + * 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 gemini 3 model to be used in the examples. */ + public static final String GEMINI_3_MODEL_NAME = "gemini-3-pro-preview"; + + /** 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-2.5-flash-native-audio-preview-09-2025"; + + /** The name of the image generation model to be used in the examples. */ + public static final String GEMINI_IMAGE_GENERATION_MODEL_NAME = "gemini-2.5-flash-image"; + + /** 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 Virtual try-on model to be used in the examples. */ + public static final String VIRTUAL_TRY_ON_MODEL_NAME = "virtual-try-on-001"; + + /** 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-3.1-generate-preview"; + + /** The name of the embedding model to be used in the examples. */ + public static final String EMBEDDING_MODEL_NAME = "text-embedding-004"; + + /** The name of the vertex multimodal embedding model to be used in the examples. */ + public static final String VERTEX_MULTIMODAL_EMBEDDING_MODEL_NAME = + "gemini-embedding-2-exp-11-2025"; + + /** 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 9ea06ce150b..1e80883700c 100644 --- a/examples/src/main/java/com/google/genai/examples/CountTokens.java +++ b/examples/src/main/java/com/google/genai/examples/CountTokens.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.CountTokens" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -45,6 +46,13 @@ /** 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) { + 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 @@ -62,7 +70,7 @@ public static void main(String[] args) { } CountTokensResponse response = - client.models.countTokens("gemini-2.0-flash-001", "What is your name?", null); + client.models.countTokens(modelId, "What is your name?", null); System.out.println("Count tokens response: " + response); } 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 e43cc9399b9..1ac426d41c3 100644 --- a/examples/src/main/java/com/google/genai/examples/CountTokensWithConfigs.java +++ b/examples/src/main/java/com/google/genai/examples/CountTokensWithConfigs.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.CountTokensWithConfigs" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -53,6 +54,13 @@ */ public final class CountTokensWithConfigs { 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 @@ -66,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. @@ -78,7 +89,7 @@ public static void main(String[] args) { .build(); CountTokensResponse response = - client.models.countTokens("gemini-2.0-flash-001", "Tell me the history of LLM", config); + client.models.countTokens(modelId, "Tell me the history of LLM", config); System.out.println("Response: " + response); } 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 9391e0d8fba..0761645158d 100644 --- a/examples/src/main/java/com/google/genai/examples/EditImageAsync.java +++ b/examples/src/main/java/com/google/genai/examples/EditImageAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.EditImageAsync" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -49,14 +50,19 @@ import com.google.genai.types.MaskReferenceMode; import com.google.genai.types.RawReferenceImage; import com.google.genai.types.ReferenceImage; -import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.CompletableFuture; -import org.apache.http.HttpException; /** 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) throws IOException, HttpException { + public static void main(String[] args) { + 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 // 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 @@ -70,7 +76,8 @@ public static void main(String[] args) throws IOException, HttpException { 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: @@ -102,10 +109,7 @@ public static void main(String[] args) throws IOException, HttpException { CompletableFuture editImageResponseFuture = client.async.models.editImage( - "imagen-3.0-capability-001", - "Sunlight and clear sky", - referenceImages, - editImageConfig); + modelId, "Sunlight and clear sky", referenceImages, editImageConfig); editImageResponseFuture .thenAccept( 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 2f6f79d9fb5..81842b18500 100644 --- a/examples/src/main/java/com/google/genai/examples/EditImageControlReference.java +++ b/examples/src/main/java/com/google/genai/examples/EditImageControlReference.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.EditImageControlReference" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -54,6 +55,13 @@ /** 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) { + 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 // 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 @@ -67,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: @@ -93,7 +102,7 @@ public static void main(String[] args) { EditImageResponse editImageResponse = client.models.editImage( - "imagen-3.0-capability-001", + modelId, "Change the colors aligning with the scribble map [1].", referenceImages, editImageConfig); 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 d7d64d12caf..e0044276578 100644 --- a/examples/src/main/java/com/google/genai/examples/EditImageMaskReference.java +++ b/examples/src/main/java/com/google/genai/examples/EditImageMaskReference.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.EditImageMaskReference" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -56,6 +57,13 @@ /** 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) { + 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 // 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 @@ -69,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: @@ -101,10 +110,7 @@ public static void main(String[] args) { EditImageResponse editImageResponse = client.models.editImage( - "imagen-3.0-capability-001", - "Sunlight and clear sky", - referenceImages, - editImageConfig); + modelId, "Sunlight and clear sky", referenceImages, editImageConfig); Image editedImage = editImageResponse.generatedImages().get().get(0).image().get(); // Do something with editedImage. 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 e89667a36dc..0e69cf8754b 100644 --- a/examples/src/main/java/com/google/genai/examples/EditImageStyleTransfer.java +++ b/examples/src/main/java/com/google/genai/examples/EditImageStyleTransfer.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.EditImageStyleTransfer" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -53,6 +54,13 @@ /** 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) { + 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 // 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 @@ -66,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: @@ -88,7 +97,7 @@ public static void main(String[] args) { EditImageResponse editImageResponse = client.models.editImage( - "imagen-3.0-capability-001", + modelId, "Generate an image in the style of [1] based on the following caption: A church in the" + " mountain.", referenceImages, 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 1ef36675738..0ba00a64f2f 100644 --- a/examples/src/main/java/com/google/genai/examples/EditImageSubjectReference.java +++ b/examples/src/main/java/com/google/genai/examples/EditImageSubjectReference.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.EditImageSubjectReference" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -54,6 +55,13 @@ /** 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) { + 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 // 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 @@ -67,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: @@ -92,7 +101,7 @@ public static void main(String[] args) { EditImageResponse editImageResponse = client.models.editImage( - "imagen-3.0-capability-001", + modelId, "Generate an image containing a mug with the product logo [1] visible on the side of" + " the mug.", referenceImages, 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 7f5e621a55c..2cf4cba131f 100644 --- a/examples/src/main/java/com/google/genai/examples/EmbedContent.java +++ b/examples/src/main/java/com/google/genai/examples/EmbedContent.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,15 +36,27 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.EmbedContent" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; import com.google.genai.Client; +import com.google.genai.types.Content; import com.google.genai.types.EmbedContentResponse; +import com.google.genai.types.FileData; +import com.google.genai.types.Part; +import java.util.Arrays; /** An example of using the Unified Gen AI Java SDK to embed content. */ public final class EmbedContent { public static void main(String[] args) { + 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 // 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 @@ -62,9 +74,27 @@ public static void main(String[] args) { } EmbedContentResponse response = - client.models.embedContent("text-embedding-004", "why is the sky blue?", null); + client.models.embedContent(modelId, "why is the sky blue?", null); System.out.println("Embedding response: " + response); + + if (client.vertexAI()) { + System.out.println("Embed content with GCS image example."); + Part textPart = Part.builder().text("What is in this image?").build(); + Part imagePart = + Part.builder() + .fileData( + FileData.builder() + .fileUri("gs://cloud-samples-data/generative-ai/image/a-man-and-a-dog.png") + .mimeType("image/png") + .build()) + .build(); + Content content = Content.builder().parts(Arrays.asList(textPart, imagePart)).build(); + response = + client.models.embedContent( + Constants.VERTEX_MULTIMODAL_EMBEDDING_MODEL_NAME, content, null); + System.out.println("Embedding response with GCS image: " + response); + } } private EmbedContent() {} 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 b8fe0dbb1e4..2a77865a4ff 100644 --- a/examples/src/main/java/com/google/genai/examples/EmbedContentAsync.java +++ b/examples/src/main/java/com/google/genai/examples/EmbedContentAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,16 +36,28 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.EmbedContentAsync" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; import com.google.genai.Client; +import com.google.genai.types.Content; import com.google.genai.types.EmbedContentResponse; +import com.google.genai.types.FileData; +import com.google.genai.types.Part; +import java.util.Arrays; import java.util.concurrent.CompletableFuture; /** An example of using the Unified Gen AI Java SDK to embed content asynchronously. */ public final class EmbedContentAsync { public static void main(String[] args) { + 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 // 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 @@ -63,7 +75,7 @@ public static void main(String[] args) { } CompletableFuture responseFuture = - client.async.models.embedContent("text-embedding-004", "Why is the sky blue?", null); + client.async.models.embedContent(modelId, "Why is the sky blue?", null); responseFuture .thenAccept( @@ -71,6 +83,28 @@ public static void main(String[] args) { System.out.println("Async embedding response: " + response); }) .join(); + + // Vertex Multimodal embedding. + if (client.vertexAI()) { + System.out.println("Embed content with GCS image example."); + Part textPart = Part.builder().text("What is in this image?").build(); + Part imagePart = + Part.builder() + .fileData( + FileData.builder() + .fileUri("gs://cloud-samples-data/generative-ai/image/a-man-and-a-dog.png") + .mimeType("image/png") + .build()) + .build(); + Content content = Content.builder().parts(Arrays.asList(textPart, imagePart)).build(); + responseFuture = + client.async.models.embedContent(Constants.VERTEX_MULTIMODAL_EMBEDDING_MODEL_NAME, content, null); + responseFuture + .thenAccept( + response -> + System.out.println("Async embedding response with GCS image: " + response)) + .join(); + } } private EmbedContentAsync() {} 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 797eae0502b..09770d6512d 100644 --- a/examples/src/main/java/com/google/genai/examples/EmbedContentWithConfig.java +++ b/examples/src/main/java/com/google/genai/examples/EmbedContentWithConfig.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.EmbedContentWithConfig" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -49,6 +50,13 @@ /** 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) { + 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 // 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 @@ -69,9 +77,7 @@ public static void main(String[] args) { EmbedContentResponse response = client.models.embedContent( - "text-embedding-004", - ImmutableList.of("why is the sky blue?", "What is your age?"), - config); + modelId, ImmutableList.of("why is the sky blue?", "What is your age?"), config); System.out.println("Embedding response: " + response); } 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 4d1dd4c5f06..0a54cb0b1a4 100644 --- a/examples/src/main/java/com/google/genai/examples/FileOperations.java +++ b/examples/src/main/java/com/google/genai/examples/FileOperations.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -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 9d0384c1861..f35c7ed057a 100644 --- a/examples/src/main/java/com/google/genai/examples/FileOperationsAsync.java +++ b/examples/src/main/java/com/google/genai/examples/FileOperationsAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -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/FileSearchStores.java b/examples/src/main/java/com/google/genai/examples/FileSearchStores.java new file mode 100644 index 00000000000..5a6a7b24e6f --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/FileSearchStores.java @@ -0,0 +1,164 @@ +/* + * 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.FileSearchStores" + * -Dexec.args="path/to/file" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.Document; +import com.google.genai.types.File; +import com.google.genai.types.FileSearchStore; +import com.google.genai.types.ImportFileOperation; +import com.google.genai.types.ListFileSearchStoresConfig; +import com.google.genai.types.UploadFileConfig; +import com.google.genai.types.UploadToFileSearchStoreOperation; + +/** + * An example of how to use the FileSearchStores module to upload, retrieve, and delete file search + * stores. + */ +public final class FileSearchStores { + public static void main(String[] args) { + final String filePath; + if (args.length != 0) { + filePath = args[0]; + } else { + filePath = Constants.UPLOAD_FILE_PATH; + } + + // 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("Vertex AI API is not supported for this example."); + System.exit(0); + } else { + System.out.println("Using Gemini Developer API"); + } + + try { + FileSearchStore fileSearchStore = client.fileSearchStores.create(null); + System.out.println("Created file store: " + fileSearchStore.name().get()); + + // Get the uploaded file search store. + FileSearchStore retrievedFileStore = + client.fileSearchStores.get(fileSearchStore.name().get(), null); + System.out.println("Retrieved file store: " + retrievedFileStore.name().get()); + + // List all file stores. + System.out.println("List file stores: "); + for (FileSearchStore f : + client.fileSearchStores.list(ListFileSearchStoresConfig.builder().pageSize(10).build())) { + System.out.println(" File store name: " + f.name().get()); + } + + // Upload a file to the Files Service. + File file = + client.files.upload(filePath, UploadFileConfig.builder().mimeType("text/plain").build()); + System.out.println("Uploaded file: " + file.name().get()); + + // Import the uploaded file to the file search store. + ImportFileOperation importOperation = + client.fileSearchStores.importFile(fileSearchStore.name().get(), file.name().get(), null); + System.out.println("Import file operation: " + importOperation.name().get()); + while (importOperation.done().filter(Boolean::booleanValue).isEmpty()) { + try { + Thread.sleep(5000); // Sleep for 5 seconds. + importOperation = client.operations.get(importOperation, null); + System.out.println("Waiting for import operation to complete..."); + } catch (InterruptedException e) { + System.out.println("Thread was interrupted while sleeping."); + Thread.currentThread().interrupt(); + } + } + + // Upload a file to the file search store. + UploadToFileSearchStoreOperation uploadOperation = + client.fileSearchStores.uploadToFileSearchStore( + fileSearchStore.name().get(), filePath, null); + System.out.println("Upload to file search store operation: " + uploadOperation.name().get()); + while (uploadOperation.done().filter(Boolean::booleanValue).isEmpty()) { + try { + Thread.sleep(5000); // Sleep for 5 seconds. + uploadOperation = client.operations.get(uploadOperation, null); + System.out.println("Waiting for upload operation to complete..."); + } catch (InterruptedException e) { + System.out.println("Thread was interrupted while sleeping."); + Thread.currentThread().interrupt(); + } + } + + String documentName = uploadOperation.response().get().documentName().get(); + System.out.println("Uploaded document: " + documentName); + + // Get document + Document retrievedDocument = client.fileSearchStores.documents.get(documentName, null); + System.out.println("Retrieved document: " + retrievedDocument.name().get()); + + // List documents + System.out.println("List documents: "); + for (Document d : + client.fileSearchStores.documents.list(fileSearchStore.name().get(), null)) { + System.out.println(" Document name: " + d.name().get()); + } + + // Delete the imported document + client.fileSearchStores.documents.delete(documentName, null); + System.out.println("Deleted document: " + documentName); + + // Delete the file search store + client.fileSearchStores.delete(fileSearchStore.name().get(), null); + System.out.println("Deleted file: " + fileSearchStore.name().get()); + } catch (GenAiIOException e) { + System.out.println("An error occurred while uploading the file: " + e.getMessage()); + } + } + + private FileSearchStores() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/FileSearchStoresAsync.java b/examples/src/main/java/com/google/genai/examples/FileSearchStoresAsync.java new file mode 100644 index 00000000000..2d2d048dedf --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/FileSearchStoresAsync.java @@ -0,0 +1,216 @@ +/* + * 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.FileSearchStoresAsync" + * -Dexec.args="path/to/file" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.File; +import com.google.genai.types.FileSearchStore; +import com.google.genai.types.ListFileSearchStoresConfig; +import com.google.genai.types.Operation; +import com.google.genai.types.UploadFileConfig; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +/** + * An example of how to use the FileSearchStores module to upload, retrieve, and delete file search + * stores. + */ +public final class FileSearchStoresAsync { + + private static > CompletableFuture awaitOperationComplete( + Client client, T operation) { + if (operation.done().orElse(false)) { + System.out.println("Operation " + operation.name().get() + " completed."); + return CompletableFuture.completedFuture(operation); + } + + System.out.println("Waiting for operation to complete..."); + return CompletableFuture.supplyAsync( + () -> operation, CompletableFuture.delayedExecutor(5, TimeUnit.SECONDS)) + .thenApply( + op -> { + try { + return client.async.operations.get(op, null).get(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException("Failed to get operation status", e); + } + }) + .thenCompose(newOp -> awaitOperationComplete(client, (T) newOp)); + } + + public static void main(String[] args) throws Exception { + String filePath = args.length > 0 ? args[0] : Constants.UPLOAD_FILE_PATH; + + try (Client client = new Client()) { + if (client.vertexAI()) { + System.out.println("Vertex AI API is not supported for this example."); + return; + } + System.out.println("Using Gemini Developer API"); + + // Create store + CompletableFuture finalFuture = + client + .async + .fileSearchStores + .create(null) + .thenCompose( + store -> { + System.out.println("Created file store: " + store.name().get()); + + // Get store + return client + .async + .fileSearchStores + .get(store.name().get(), null) + .thenAccept( + retrievedStore -> + System.out.println( + "Retrieved file store: " + retrievedStore.name().get() + ")")) + + // List stores. + .thenCompose( + v -> + client.async.fileSearchStores.list( + ListFileSearchStoresConfig.builder().pageSize(10).build())) + .thenCompose( + pager -> { + System.out.println("List file stores: "); + return pager.forEach( + item -> + System.out.println( + " File store name: " + item.name().get())); + }) + .thenApply(v -> store); + }) + .thenCompose( + store -> { + // Upload File + return client + .async + .files + .upload(filePath, UploadFileConfig.builder().mimeType("text/plain").build()) + .thenApply( + file -> { + System.out.println("Uploaded file: " + file.name().get()); + return new Object[] {store, file}; + }); + }) + .thenCompose( + objects -> { + FileSearchStore store = (FileSearchStore) objects[0]; + File file = (File) objects[1]; + + // Import File + return client + .async + .fileSearchStores + .importFile(store.name().get(), file.name().get(), null) + .thenCompose(operation -> awaitOperationComplete(client, operation)) + .thenApply( + completedOp -> { + System.out.println("Import File: LRO Completed."); + return store; + }); + }) + + // Direct upload file to the store + .thenCompose( + store -> { + return client + .async + .fileSearchStores + .uploadToFileSearchStore(store.name().get(), filePath, null) + .thenCompose(operation -> awaitOperationComplete(client, operation)) + .thenApply( + completedOp -> { + String docName = completedOp.response().get().documentName().get(); + System.out.println("Direct Upload: Completed document " + docName); + return new Object[] {store, docName}; + }); + }) + .thenCompose( + objects -> { + FileSearchStore store = (FileSearchStore) objects[0]; + String docName = (String) objects[1]; + return client + .async + .fileSearchStores + .documents + .get(docName, null) + .thenAccept( + doc -> + System.out.println( + "Get Document: Success (" + doc.name().get() + ")")) + + // List documents + .thenCompose( + v -> + client.async.fileSearchStores.documents.list( + store.name().get(), null)) + .thenCompose( + pager -> { + System.out.println("List all document names: "); + return pager.forEach( + item -> + System.out.println(" document name: " + item.name().get())); + }) + + // Delete document + .thenCompose( + v -> client.async.fileSearchStores.documents.delete(docName, null)) + .thenRun(() -> System.out.println("Delete Document: Success.")) + + // Delete store + .thenCompose( + v -> client.async.fileSearchStores.delete(store.name().get(), null)) + .thenAccept(v -> System.out.println("Delete Store: Success.")); + }); + finalFuture.get(); + } + System.out.println("Async execution for file search stores completed successfully."); + } + + private FileSearchStoresAsync() {} +} 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 6459b407710..f89c986fd14 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContent.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContent.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContent" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -45,6 +46,13 @@ /** An example of using the Unified Gen AI Java SDK to generate content. */ public final class GenerateContent { 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 @@ -62,10 +70,17 @@ public static void main(String[] args) { } GenerateContentResponse response = - client.models.generateContent("gemini-2.0-flash-001", "What is your name?", null); + client.models.generateContent(modelId, "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))); } private GenerateContent() {} 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 f50354da19b..655c99ce3f8 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentAsync.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentAsync" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -46,6 +47,13 @@ /** An example of using the Unified Gen AI Java SDK to generate content asynchronously. */ public final class GenerateContentAsync { 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 @@ -63,13 +71,20 @@ public static void main(String[] args) { } CompletableFuture responseFuture = - client.async.models.generateContent( - "gemini-2.0-flash-001", "Introduce Google AI Studio.", null); + client.async.models.generateContent(modelId, "Introduce Google AI Studio.", null); responseFuture .thenAccept( response -> { + // Gets the text string from the response System.out.println("Async response: " + response.text()); + // Gets the http headers from the response. + response + .sdkHttpResponse() + .ifPresent( + httpResponse -> + System.out.println( + "Response headers: " + httpResponse.headers().orElse(null))); }) .join(); } 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 a226663c4d8..421b4202594 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentStream.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentStream.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentStream" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -46,6 +47,13 @@ /** An example of using the Unified GenAI Java SDK to generate stream of content. */ public final class GenerateContentStream { 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 @@ -63,12 +71,18 @@ public static void main(String[] args) { } ResponseStream responseStream = - client.models.generateContentStream( - "gemini-2.0-flash-001", "Tell me a story in 300 words.", null); + client.models.generateContentStream(modelId, "Tell me a story in 300 words.", null); System.out.println("Streaming response: "); for (GenerateContentResponse res : responseStream) { + // Gets the text string from the response by the quick accessor method `text()`. System.out.print(res.text()); + + // Gets the http headers from the response. + res.sdkHttpResponse() + .ifPresent( + httpResponse -> + System.out.println("Response headers: " + httpResponse.headers().orElse(null))); } // To save resources and avoid connection leaks, it is recommended to close the response diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentStreamingFunctionCall.java b/examples/src/main/java/com/google/genai/examples/GenerateContentStreamingFunctionCall.java new file mode 100644 index 00000000000..58da1ae1b6d --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentStreamingFunctionCall.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. + */ + +/** + * 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.GenerateContentStreamingFunctionCall" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.ResponseStream; +import com.google.genai.types.FunctionCallingConfig; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.Tool; +import com.google.genai.types.ToolConfig; +import java.lang.reflect.Method; + +/** An example of using the Unified Gen AI Java SDK to generate content. */ +public final class GenerateContentStreamingFunctionCall { + /** A callable function to get the current weather. */ + public static String getCurrentWeather(String location) { + return "The weather in " + location + " is " + "very nice."; + } + + public static void main(String[] args) throws NoSuchMethodException { + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_3_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 does not support streaming function calling."); + return; + } + + // Add the methods as callable functions to the tool. + Method method1 = + GenerateContentStreamingFunctionCall.class.getDeclaredMethod( + "getCurrentWeather", String.class); + + GenerateContentConfig config = + GenerateContentConfig.builder() + .tools(Tool.builder().functions(method1)) + .toolConfig( + ToolConfig.builder() + .functionCallingConfig( + FunctionCallingConfig.builder().streamFunctionCallArguments(true))) + .build(); + + ResponseStream responseStream = + client.models.generateContentStream( + modelId, "What is the weather in San Francisco?", config); + + System.out.println("Streaming response: "); + for (GenerateContentResponse res : responseStream) { + // Gets the function calls from the response by the quick accessor method `text()`. + System.out.print(res.functionCalls()); + + // Gets the http headers from the response. + res.sdkHttpResponse() + .ifPresent( + httpResponse -> + System.out.println("Response headers: " + httpResponse.headers().orElse(null))); + } + + // To save resources and avoid connection leaks, it is recommended to close the response + // stream after consumption (or using try block to get the response stream). + responseStream.close(); + } + + private GenerateContentStreamingFunctionCall() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithClientOptions.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithClientOptions.java new file mode 100644 index 00000000000..95e98aeae6f --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithClientOptions.java @@ -0,0 +1,85 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * 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.GenerateContentWithClientOptions" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.ClientOptions; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.ProxyOptions; +import com.google.genai.types.ProxyType; + +/** An example of setting client options in a GenerateContent request. */ +public final class GenerateContentWithClientOptions { + 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 options when creating the client. This applies to all requests made through + // this client. + ClientOptions clientOptions = + ClientOptions.builder() + .proxyOptions(ProxyOptions.builder().type(ProxyType.Known.DIRECT)) + .maxConnections(10) + .maxConnectionsPerHost(5) + .build(); + + Client client = Client.builder().clientOptions(clientOptions).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 GenerateContentWithClientOptions() {} +} 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 dd7c123121e..770bbeb5751 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithConfigs.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithConfigs.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentWithConfigs" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -56,6 +57,13 @@ /** 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) { + 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 @@ -100,7 +108,7 @@ public static void main(String[] args) { .build(); GenerateContentResponse response = - client.models.generateContent("gemini-2.0-flash-001", "Tell me the history of LLM", config); + client.models.generateContent(modelId, "Tell me the history of LLM", config); System.out.println("Response: " + response.text()); } 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 5e532ef4607..1efca4069de 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCall.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCall.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentWithFunctionCall" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -46,6 +47,8 @@ import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.Tool; import java.lang.reflect.Method; +import java.util.List; +import java.util.ArrayList; /** An example of using the Unified Gen AI Java SDK to generate content with function calling. */ public final class GenerateContentWithFunctionCall { @@ -55,11 +58,26 @@ 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 Integer sumInts(List items) { + int sum = 0; + for (Integer item : items) { + sum += item; + } + return sum; + } + public static void main(String[] args) throws NoSuchMethodException { + 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 @@ -76,21 +94,27 @@ 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); + + Method method3 = GenerateContentWithFunctionCall.class.getMethod("sumInts", List.class); // Add the two methods as callable functions to the list of tools. GenerateContentConfig config = - GenerateContentConfig.builder().tools(Tool.builder().functions(method1, method2)).build(); + GenerateContentConfig.builder() + .tools(Tool.builder().functions(method1, method2, method3)) + .build(); GenerateContentResponse response = client.models.generateContent( - "gemini-2.0-flash-001", - "What is the weather in Vancouver? And can you divide 10 by 0?", + modelId, + "What is the weather in Vancouver? And can you divide 10 by 0? And can you sum the" + + " integers 1, 2, 3, 4, and 5?", config); System.out.println("The response is: " + response.text()); 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 new file mode 100644 index 00000000000..6dd91f1c7bf --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithFunctionCallJson.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. + */ + +/** + * 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.GenerateContentWithFunctionCallJson" + * -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.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 GenerateContentWithFunctionCallJson { + /** 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. + 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( + FunctionDeclaration.builder() + .name("get_weather") + .description("Returns the weather in a given location.") + .parametersJsonSchema(parametersSchema) + .responseJsonSchema(responseSchema) + .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 GenerateContentWithFunctionCallJson() {} +} 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..a45e5334e59 --- /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(10000) + .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 a8cd337da8d..316dbb1ccbd 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithImageInput.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithImageInput.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentWithImageInput" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -49,6 +50,13 @@ /** 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) { + 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 @@ -62,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 = @@ -72,8 +81,7 @@ public static void main(String[] args) { Part.fromText("describe the image"), Part.fromUri("gs://cloud-samples-data/generative-ai/image/scones.jpg", "image/jpeg")); - GenerateContentResponse response = - client.models.generateContent("gemini-2.0-flash-001", content, null); + GenerateContentResponse response = client.models.generateContent(modelId, content, null); System.out.println("Response: " + response.text()); } diff --git a/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseJsonSchema.java b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseJsonSchema.java new file mode 100644 index 00000000000..b6ec9707d3f --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseJsonSchema.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.GenerateContentWithResponseJsonSchema" + * -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; + +/** + * GenerateContentWithResponseJsonSchema generates a content and returns a json object by passing a + * schema. + */ +public final class GenerateContentWithResponseJsonSchema { + 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"); + } + + ImmutableMap schema = ImmutableMap.of( + "type", "object", + "properties", ImmutableMap.of( + "recipe_name", ImmutableMap.of("type", "string"), + "ingredients", ImmutableMap.of( + "type", "array", + "items", ImmutableMap.of("type", "string") + ) + ), + "required", ImmutableList.of("recipe_name", "ingredients") + ); + GenerateContentConfig config = + GenerateContentConfig.builder() + .responseMimeType("application/json") + .candidateCount(1) + .responseJsonSchema(schema) + .build(); + + GenerateContentResponse response = + client.models.generateContent(modelId, "List a few popular cookie recipes.", config); + + System.out.println("Response: " + response.text()); + } + + private GenerateContentWithResponseJsonSchema() {} +} 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 89b65325a64..55c5e1d08c3 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseModality.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseModality.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentWithResponseModality" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -48,6 +49,13 @@ /** 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) { + 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 // 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 @@ -68,10 +76,7 @@ public static void main(String[] args) { GenerateContentConfig.builder().responseModalities("TEXT", "IMAGE").build(); GenerateContentResponse response = - client.models.generateContent( - "gemini-2.0-flash-preview-image-generation", - "Generate a cat image and describe it.", - config); + client.models.generateContent(modelId, "Generate a cat image and describe it.", config); System.out.println("Response: " + response.toJson()); } 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 10a1ed807fd..ea44ba2c6d2 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseSchema.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateContentWithResponseSchema.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentWithResponseSchema" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -54,6 +55,13 @@ */ public final class GenerateContentWithResponseSchema { 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 @@ -95,8 +103,7 @@ public static void main(String[] args) { .build(); GenerateContentResponse response = - client.models.generateContent( - "gemini-2.0-flash-001", "List a few popular cookie recipes.", config); + client.models.generateContent(modelId, "List a few popular cookie recipes.", config); System.out.println("Response: " + response.text()); } 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 b050211ab68..d6704632746 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateImages.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateImages.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateImages" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -47,6 +48,13 @@ /** An example of using the Unified Gen AI Java SDK to generate images. */ public final class GenerateImages { public static void main(String[] args) { + 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 // 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 @@ -72,12 +80,13 @@ public static void main(String[] args) { GenerateImagesResponse generatedImagesResponse = client.models.generateImages( - "imagen-3.0-generate-002", "Robot holding a red skateboard", generateImagesConfig); + modelId, "Robot holding a red skateboard", generateImagesConfig); - System.out.println( - "Generated " + generatedImagesResponse.generatedImages().get().size() + " images."); - - Image generatedImage = generatedImagesResponse.generatedImages().get().get(0).image().get(); + if (generatedImagesResponse.images().isEmpty()) { + System.out.println("Unable to generate images."); + } + System.out.println("Generated " + generatedImagesResponse.images().size() + " images."); + Image generatedImage = generatedImagesResponse.images().get(0); // Do something with the image. System.out.println( 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 4320bda8c6d..2556b5e472a 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateImagesAsync.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateImagesAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateImagesAsync" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -48,6 +49,13 @@ /** An example of using the Unified Gen AI Java SDK to generate images asynchronously. */ public final class GenerateImagesAsync { public static void main(String[] args) { + 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 // 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 @@ -73,7 +81,7 @@ public static void main(String[] args) { CompletableFuture generateImagesResponseFuture = client.async.models.generateImages( - "imagen-3.0-generate-002", "Robot holding a red skateboard", generateImagesConfig); + modelId, "Robot holding a red skateboard", generateImagesConfig); generateImagesResponseFuture .thenAccept( 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 3f7faf64a06..b515c3dfc29 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateVideos.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateVideos.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,18 +36,28 @@ *

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.JsonSerializable; 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) { + 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 // 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 @@ -64,6 +74,11 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } + // Optinoal: If the default 20MB limit is not enough for the generated video response, you can + // increase the limit via system property `genai.json.maxReadLength` or via this static method + // `JsonSerializable.setMaxReadLength`. + JsonSerializable.setMaxReadLength(100_000_000); + GenerateVideosConfig.Builder generateVideosConfigBuilder = GenerateVideosConfig.builder().numberOfVideos(1); @@ -71,20 +86,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( - "veo-2.0-generate-001", - "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."); @@ -98,11 +112,14 @@ public static void main(String[] args) { Video generatedVideo = generateVideosOperation.response().get().generatedVideos().get().get(0).video().get(); - try { - client.files.download(generatedVideo, "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()); + + if (!client.vertexAI()) { + try { + client.files.download(generatedVideo, "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()); + } } } 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 4897db41b92..55b99cfa087 100644 --- a/examples/src/main/java/com/google/genai/examples/GenerateVideosAsync.java +++ b/examples/src/main/java/com/google/genai/examples/GenerateVideosAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,12 +36,15 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateVideosAsync" + * -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.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; @@ -49,6 +52,13 @@ /** An example of using the Unified Gen AI Java SDK to generate images asynchronously. */ public final class GenerateVideosAsync { public static void main(String[] args) { + 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 // 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 @@ -65,6 +75,11 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } + // Optinoal: If the default 20MB limit is not enough for the generated video response, you can + // increase the limit via system property `genai.json.maxReadLength` or via this static method + // `JsonSerializable.setMaxReadLength`. + JsonSerializable.setMaxReadLength(100_000_000); + GenerateVideosConfig.Builder generateVideosConfigBuilder = GenerateVideosConfig.builder().numberOfVideos(1); @@ -72,13 +87,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( - "veo-2.0-generate-001", - "A neon hologram of a cat driving at top speed", - null, - generateVideosConfig); + client.async.models.generateVideos(modelId, generateVideosSource, generateVideosConfig); generateVideosOperationFuture .thenAccept( @@ -89,7 +104,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); } @@ -106,7 +121,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..ab46adec263 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateVideosEditOutpaint.java @@ -0,0 +1,139 @@ +/* + * 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.JsonSerializable; +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-preview"; // Only supported on preview 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); + } + + // Optinoal: If the default 20MB limit is not enough for the generated video response, you can + // increase the limit via system property `genai.json.maxReadLength` or via this static method + // `JsonSerializable.setMaxReadLength`. + JsonSerializable.setMaxReadLength(100_000_000); + + 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..869e1d53ad4 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/GenerateVideosExtension.java @@ -0,0 +1,163 @@ +/* + * 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.GenerateVideosExtension" -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.JsonSerializable; +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 extend a video. */ +public final class GenerateVideosExtension { + public static void main(String[] args) { + 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 + // 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"); + } + + // Optional: If the default 20MB limit is not enough for the generated video response, you can + // increase the limit via system property `genai.json.maxReadLength` or via this static method + // `JsonSerializable.setMaxReadLength`. + JsonSerializable.setMaxReadLength(100_000_000); + + // 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 619f84f4291..e1a6c82e0a9 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveAudioConversationAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveAudioConversationAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -39,6 +39,7 @@ *

mvn clean * *

mvn compile exec:java -Dexec.mainClass="com.google.genai.examples.LiveAudioConversationAsync" + * -Dexec.args="YOUR_MODEL_ID" * *

3. Speak into the microphone. Press Ctrl+C to exit. Important: This example uses the system * default audio input and output, which often won't include echo cancellation. So to prevent the @@ -46,17 +47,22 @@ */ package com.google.genai.examples; -import com.google.common.collect.ImmutableList; 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; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -84,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; @@ -111,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); @@ -135,7 +139,6 @@ private static void sendMicrophoneAudio() { } public static void main(String[] args) throws LineUnavailableException { - // 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 @@ -152,6 +155,15 @@ public static void main(String[] args) throws LineUnavailableException { System.out.println("Using Gemini Developer API"); } + 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 --- microphoneLine = getMicrophoneLine(); speakerLine = getSpeakerLine(); @@ -161,7 +173,7 @@ public static void main(String[] args) throws LineUnavailableException { String voiceName = "Aoede"; LiveConnectConfig config = LiveConnectConfig.builder() - .responseModalitiesFromKnown(ImmutableList.of(Modality.Known.AUDIO)) + .responseModalities(Modality.Known.AUDIO) .speechConfig( SpeechConfig.builder() .voiceConfig( @@ -169,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 --- @@ -209,11 +229,7 @@ public static void main(String[] args) throws LineUnavailableException { // --- Connect to Gemini Live API --- System.out.println("Connecting to Gemini Live API..."); - if (client.vertexAI()) { - session = client.async.live.connect("gemini-2.0-flash-live-preview-04-09", config).get(); - } else { - session = client.async.live.connect("gemini-2.0-flash-live-001", config).get(); - } + session = client.async.live.connect(modelId, config).get(); System.out.println("Connected."); // --- Start Audio Lines --- @@ -295,29 +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_compete with - // Stop the speaker if the turn is complete - if (speakerLine != null && speakerLine.isOpen()) { - speakerLine.flush(); - } - } else { - content - .modelTurn() - .flatMap(modelTurn -> modelTurn.parts()) - .ifPresent( - parts -> - parts.forEach( - part -> - part.inlineData() - .flatMap(Blob::data) - .ifPresent( - 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/LiveEphemeralTokenAsync.java b/examples/src/main/java/com/google/genai/examples/LiveEphemeralTokenAsync.java new file mode 100644 index 00000000000..b5c302e2cf2 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/LiveEphemeralTokenAsync.java @@ -0,0 +1,191 @@ +/* + * 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.LiveEphemeralTokenAsync" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.common.collect.ImmutableList; +import com.google.genai.AsyncSession; +import com.google.genai.Client; +import com.google.genai.types.AuthToken; +import com.google.genai.types.Content; +import com.google.genai.types.CreateAuthTokenConfig; +import com.google.genai.types.HttpOptions; +import com.google.genai.types.LiveConnectConfig; +import com.google.genai.types.LiveConnectConstraints; +import com.google.genai.types.LiveSendClientContentParameters; +import com.google.genai.types.LiveServerContent; +import com.google.genai.types.LiveServerMessage; +import com.google.genai.types.Modality; +import com.google.genai.types.Part; +import java.util.concurrent.CompletableFuture; + +/** Example of using the live module to send and receive text messages asynchronously. */ +public final class LiveEphemeralTokenAsync { + + public static void main(String[] args) { + // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API + // key from the environment variable `GOOGLE_API_KEY`. Vertex AI API can be used by setting the + // environment variables `GOOGLE_CLOUD_LOCATION` and `GOOGLE_CLOUD_PROJECT`, as well as setting + // `GOOGLE_GENAI_USE_VERTEXAI` to "true". + // + // Note: Some services are only available in a specific API backend (Gemini or Vertex), you will + // get a `UnsupportedOperationException` if you try to use a service that is not available in + // the backend you are using. + Client client = + Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1alpha").build()).build(); + + if (client.vertexAI()) { + System.out.println("Vertex AI API is not supported for this example."); + System.exit(0); + } else { + System.out.println("Using Gemini Developer API"); + } + System.out.println("Creating auth token..."); + + // Create an auth token for the live session. + AuthToken authToken = + client.authTokens.create( + CreateAuthTokenConfig.builder() + .uses(2) + .liveConnectConstraints( + LiveConnectConstraints.builder() + .model(Constants.GEMINI_LIVE_MODEL_NAME_PREVIEW) + .config( + LiveConnectConfig.builder() + .systemInstruction( + Content.fromParts( + Part.fromText( + "Answer questions like C-3PO from Star Wars would."))) + .responseModalities(Modality.Known.AUDIO) + .build()) + .build()) + .lockAdditionalFields(ImmutableList.of("topP")) + .build()); + System.out.println("Created auth token: " + authToken.name()); + + final String modelId; + if (args.length != 0) { + modelId = args[0]; + } else { + modelId = Constants.GEMINI_LIVE_MODEL_NAME_PREVIEW; + } + + // Create a client using the ephemeral auth token. + if (authToken == null || authToken.name() == null) { + System.out.println("No auth token created."); + System.exit(0); + } + Client clientWithAuthToken = + Client.builder() + .apiKey(authToken.name().orElse(null)) + .httpOptions(HttpOptions.builder().apiVersion("v1alpha").build()) + .build(); + + // Note that the system instruction here is ignored by the server. The system instruction was + // set and locked in the LiveConnectConstraints of the CreateAuthTokenConfig. Here we are just + // demonstrating that here. Other unlocked fields (like temperature) can be configured here. + LiveConnectConfig config = + LiveConnectConfig.builder() + .systemInstruction( + Content.fromParts( + Part.fromText("You are a pirate. Answer all questions like a pirate would."))) + .build(); + + CompletableFuture allDone = new CompletableFuture<>(); + + CompletableFuture futureSession = + clientWithAuthToken.async.live.connect(modelId, config); + + futureSession + .thenCompose( + session -> { + String inputText = "What would you say if you are surprised?"; + System.out.println("Connecting to live session..."); + System.out.println(session.sessionId()); + System.out.println("\n**Input**\n" + inputText); + + return session + // Send the input message. + .sendClientContent(clientContentFromText(inputText)) + .thenCompose( + unused -> { + System.out.print("\n**Response**\n"); + // Receive messages from the live session. + return session.receive(message -> printLiveServerMessage(message, allDone)); + }) + // Wait for the allDone future to complete, which is signaled in + // printLiveServerMessage when the server is done sending messages. + .thenCompose(unused -> allDone) + // Close the session. + .thenCompose(unused -> session.close()); + }) + .join(); + } + + /** Wraps client message text. */ + public static LiveSendClientContentParameters clientContentFromText(String text) { + return LiveSendClientContentParameters.builder() + .turnComplete(true) + .turns(Content.fromParts(Part.fromText(text))) + .build(); + } + + public static void printLiveServerMessage( + LiveServerMessage message, CompletableFuture allDone) { + // Extract and print text from the model. + message + .serverContent() + .flatMap(LiveServerContent::modelTurn) + .flatMap(Content::parts) + .ifPresent(parts -> parts.forEach(part -> part.text().ifPresent(System.out::print))); + + // 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); + } + } + + private LiveEphemeralTokenAsync() {} +} 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 38390a22abe..526e4250a8e 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveTextContextWindowCompressionAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveTextContextWindowCompressionAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -39,6 +39,7 @@ * *

mvn exec:java * -Dexec.mainClass="com.google.genai.examples.LiveTextContextWindowCompressionAsync" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -76,9 +77,19 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } + 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. LiveConnectConfig config = LiveConnectConfig.builder() - .responseModalitiesFromKnown(ImmutableList.of(Modality.Known.TEXT)) + .responseModalities(Modality.Known.TEXT) .contextWindowCompression( ContextWindowCompressionConfig.builder() .triggerTokens(1000L) @@ -87,15 +98,7 @@ public static void main(String[] args) { CompletableFuture allDone = new CompletableFuture<>(); - String modelName; - if (client.vertexAI()) { - modelName = "gemini-2.0-flash-live-preview-04-09"; - } else { - modelName = "gemini-2.0-flash-live-001"; - } - - CompletableFuture futureSession = client.async.live.connect(modelName, config); - + CompletableFuture futureSession = client.async.live.connect(modelId, config); futureSession .thenCompose( session -> { @@ -111,12 +114,16 @@ public static void main(String[] args) { // Receive messages from the live session. return session.receive(message -> printLiveServerMessage(message, allDone)); }) + // Wait for the allDone future to complete, which is signaled in + // printLiveServerMessage when the server is done sending messages. .thenCompose(unused -> allDone) + // Close the session. .thenCompose(unused -> session.close()); }) .join(); } + /** Wraps client message text. */ public static LiveSendClientContentParameters clientContentFromText(String text) { return LiveSendClientContentParameters.builder() .turnComplete(true) @@ -126,23 +133,28 @@ public static LiveSendClientContentParameters clientContentFromText(String text) public static void printLiveServerMessage( LiveServerMessage message, CompletableFuture allDone) { - if (message.serverContent().isPresent()) { - LiveServerContent content = message.serverContent().get(); - if (content.modelTurn().isPresent()) { - Content modelTurn = content.modelTurn().get(); - for (Part part : modelTurn.parts().orElse(ImmutableList.of())) { - if (part.inlineData().isPresent()) { - // Print some text to indicate that audio is returned. - System.out.print("Some audio bytes in inline_data..."); - } else if (part.text().isPresent()) { - System.out.print(part.text().get()); - } + LiveServerContent content = message.serverContent().orElse(null); + if (content == null) { + return; + } + + // Print the content sent by the model. + Content modelTurn = content.modelTurn().orElse(null); + if (modelTurn != null) { + for (Part part : modelTurn.parts().orElse(ImmutableList.of())) { + if (part.inlineData().isPresent()) { + // Print some text to indicate that audio is returned. + System.out.print("Some audio bytes in inline_data..."); + } else if (part.text().isPresent()) { + System.out.print(part.text().get()); } } - if (content.turnComplete().orElse(false)) { - System.out.println(); - allDone.complete(null); - } + } + + // Check if the server's turn is complete and signal the allDone future if so. + if (content.turnComplete().orElse(false)) { + System.out.println(); + allDone.complete(null); } } 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 a059ca7057f..de2f868c277 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveTextConversationAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveTextConversationAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,10 +38,10 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.LiveTextConversationAsync" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; -import com.google.common.collect.ImmutableList; import com.google.genai.AsyncSession; import com.google.genai.Client; import com.google.genai.types.Content; @@ -75,9 +75,18 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } + 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 = LiveConnectConfig.builder() - .responseModalitiesFromKnown(ImmutableList.of(Modality.Known.TEXT)) + .responseModalities(Modality.Known.TEXT) .topP(0.8f) .seed(1234) .build(); @@ -87,11 +96,7 @@ public static void main(String[] args) { AsyncSession session; try { - if (client.vertexAI()) { - session = client.async.live.connect("gemini-2.0-flash-live-preview-04-09", config).get(); - } else { - session = client.async.live.connect("gemini-2.0-flash-live-001", config).get(); - } + session = client.async.live.connect(modelId, config).get(); // Start receiving messages. CompletableFuture receiveFuture = session.receive(message -> printLiveServerMessage(message, allDone)); @@ -114,6 +119,7 @@ public static void main(String[] args) { } } + /** Wraps client message text. */ public static LiveSendClientContentParameters clientContentFromText(String text) { return LiveSendClientContentParameters.builder() .turnComplete(true) @@ -123,22 +129,16 @@ public static LiveSendClientContentParameters clientContentFromText(String text) public static void printLiveServerMessage( LiveServerMessage message, CompletableFuture allDone) { - if (message.serverContent().isPresent()) { - LiveServerContent content = message.serverContent().get(); - content - .modelTurn() - .ifPresent( - modelTurn -> - modelTurn - .parts() - .ifPresent( - parts -> - parts.forEach(part -> part.text().ifPresent(System.out::print)))); - - if (content.turnComplete().orElse(false)) { - System.out.print("\nYour Turn >> "); - allDone.complete(null); - } + // Extract and print text from the model. + message + .serverContent() + .flatMap(LiveServerContent::modelTurn) + .flatMap(Content::parts) + .ifPresent(parts -> parts.forEach(part -> part.text().ifPresent(System.out::print))); + + if (message.serverContent().flatMap(LiveServerContent::turnComplete).orElse(false)) { + System.out.print("\nYour Turn >> "); + allDone.complete(null); } } 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 b176512b0d0..25bbc8cb5a2 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveTextConversationResumptionAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveTextConversationResumptionAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

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

to resume a session, you can use the --session_handle argument to provide the session handle * returned in the session resumption update from the server. @@ -45,11 +46,10 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.LiveTextConversationResumptionAsync" - * -Dexec.args="--session_handle=..." + * -Dexec.args="YOUR_MODEL_ID --session_handle=..." */ package com.google.genai.examples; -import com.google.common.collect.ImmutableList; import com.google.genai.AsyncSession; import com.google.genai.Client; import com.google.genai.types.Content; @@ -62,6 +62,7 @@ import com.google.genai.types.Part; import com.google.genai.types.SessionResumptionConfig; import java.io.Console; +import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -71,7 +72,18 @@ public final class LiveTextConversationResumptionAsync { public static void main(String[] args) { // Get the session handle from the command line, if provided String sessionHandle = null; - if (args.length > 0) { + if (args.length > 1) { + if (args[1].startsWith("--session_handle")) { + String[] parts = args[1].split("=", 2); + if (parts.length == 2) { + sessionHandle = parts[1]; + } else if (parts.length == 1) { + System.err.println("Error: --session_handle requires a value."); + System.err.println("Usage: mvn ... --session_handle="); + System.exit(1); + } + } + } else if (args.length == 1) { if (args[0].startsWith("--session_handle")) { String[] parts = args[0].split("=", 2); if (parts.length == 2) { @@ -100,17 +112,28 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } + 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 = SessionResumptionConfig.builder(); + // Set the session handle if provided. if (sessionHandle != null) { System.out.println("Resuming session handle: " + sessionHandle); sessionResumptionConfigBuilder.handle(sessionHandle); } SessionResumptionConfig sessionResumptionConfig = sessionResumptionConfigBuilder.build(); + // Configures live session and session resumption. LiveConnectConfig config = LiveConnectConfig.builder() - .responseModalitiesFromKnown(ImmutableList.of(Modality.Known.TEXT)) + .responseModalities(Modality.Known.TEXT) .sessionResumption(sessionResumptionConfig) .topP(0.8f) .seed(1234) @@ -121,13 +144,7 @@ public static void main(String[] args) { AsyncSession session; try { - if (client.vertexAI()) { - System.out.println("vertex"); - session = client.async.live.connect("gemini-2.0-flash-live-preview-04-09", config).get(); - } else { - System.out.println("mldev"); - session = client.async.live.connect("gemini-2.0-flash-live-001", config).get(); - } + session = client.async.live.connect(modelId, config).get(); // Start receiving messages. CompletableFuture receiveFuture = session.receive(message -> printLiveServerMessage(message, allDone)); @@ -159,6 +176,7 @@ public static void printLiveServerMessage( } } + /** Wraps client message text. */ public static LiveSendClientContentParameters clientContentFromText(String text) { return LiveSendClientContentParameters.builder() .turnComplete(true) @@ -168,14 +186,11 @@ public static LiveSendClientContentParameters clientContentFromText(String text) private static void printServerContent( LiveServerContent content, CompletableFuture allDone) { - content - .modelTurn() - .ifPresent( - modelTurn -> - modelTurn - .parts() - .ifPresent( - parts -> parts.forEach(part -> part.text().ifPresent(System.out::print)))); + // Extract and print text from the model. + content.modelTurn().flatMap(Content::parts).stream() + .flatMap(Collection::stream) + .map(Part::text) + .forEach(text -> text.ifPresent(System.out::print)); if (content.turnComplete().orElse(false)) { System.out.println("Your Turn >> "); 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 7bdd86c50ae..b6cd68d3989 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveTextToAudioTranscriptionAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveTextToAudioTranscriptionAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,18 +38,15 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.LiveTextToAudioTranscriptionAsync" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; -import com.google.common.collect.ImmutableList; import com.google.genai.AsyncSession; import com.google.genai.Client; import com.google.genai.types.AudioTranscriptionConfig; import com.google.genai.types.Content; import com.google.genai.types.GoogleSearch; -import com.google.genai.types.GroundingChunk; -import com.google.genai.types.GroundingChunkWeb; -import com.google.genai.types.GroundingMetadata; import com.google.genai.types.LiveConnectConfig; import com.google.genai.types.LiveSendClientContentParameters; import com.google.genai.types.LiveServerContent; @@ -59,7 +56,7 @@ import com.google.genai.types.SpeechConfig; import com.google.genai.types.Tool; import com.google.genai.types.Transcription; -import java.util.List; +import java.util.Collection; import java.util.Optional; import java.util.concurrent.CompletableFuture; @@ -83,14 +80,24 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } + 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. Content systemInstruction = Content.fromParts(Part.fromText("Answer in Japanese.")); // Sets the Google Search tool in the config. Tool googleSearchTool = Tool.builder().googleSearch(GoogleSearch.builder()).build(); + // Configures live session and audio transcription. LiveConnectConfig config = LiveConnectConfig.builder() - .responseModalitiesFromKnown(ImmutableList.of(Modality.Known.AUDIO)) + .responseModalities(Modality.Known.AUDIO) .outputAudioTranscription(AudioTranscriptionConfig.builder()) .systemInstruction(systemInstruction) .speechConfig(SpeechConfig.builder().languageCode("ja-JP")) @@ -99,14 +106,7 @@ public static void main(String[] args) { CompletableFuture allDone = new CompletableFuture<>(); - String modelName; - if (client.vertexAI()) { - modelName = "gemini-2.0-flash-live-preview-04-09"; - } else { - modelName = "gemini-2.0-flash-live-001"; - } - - CompletableFuture futureSession = client.async.live.connect(modelName, config); + CompletableFuture futureSession = client.async.live.connect(modelId, config); futureSession .thenCompose( @@ -123,12 +123,16 @@ public static void main(String[] args) { // Receive messages from the live session. return session.receive(message -> printLiveServerMessage(message, allDone)); }) + // Wait for the allDone future to complete, which is signaled in + // printLiveServerMessage when the server is done sending messages. .thenCompose(unused -> allDone) + // Close the session. .thenCompose(unused -> session.close()); }) .join(); } + /** Wraps client message text. */ public static LiveSendClientContentParameters clientContentFromText(String text) { return LiveSendClientContentParameters.builder() .turnComplete(true) @@ -140,34 +144,8 @@ public static void printLiveServerMessage( LiveServerMessage message, CompletableFuture allDone) { if (message.serverContent().isPresent()) { LiveServerContent content = message.serverContent().get(); - if (content.modelTurn().isPresent()) { - Content modelTurn = content.modelTurn().get(); - for (Part part : modelTurn.parts().orElse(ImmutableList.of())) { - if (part.inlineData().isPresent()) { - // Print some text to indicate that audio is returned. - System.out.print("Some audio bytes in inline_data..."); - } - } - } - if (content.groundingMetadata().isPresent()) { - GroundingMetadata groundingMetadata = content.groundingMetadata().get(); - - Optional> groundingChunksOptional = - groundingMetadata.groundingChunks(); - - if (groundingChunksOptional.isPresent()) { - List groundingChunks = groundingChunksOptional.get(); - for (GroundingChunk chunk : groundingChunks) { - if (chunk.web().isPresent()) { - GroundingChunkWeb web = chunk.web().get(); - if (web.uri().isPresent()) { - String uri = web.uri().get(); - System.out.println("\n\nGrounding URI: " + uri); - } - } - } - } - } + processModelTurn(content); + processGroundingMetadata(content); // Print audio transcription. if (content.outputTranscription().isPresent()) { @@ -176,6 +154,8 @@ public static void printLiveServerMessage( System.out.print(transcription.text().get()); } } + + // Check if the server's turn is complete and signal the allDone future if so. if (content.turnComplete().orElse(false)) { System.out.println(); allDone.complete(null); @@ -183,5 +163,26 @@ public static void printLiveServerMessage( } } + private static void processModelTurn(LiveServerContent content) { + content.modelTurn().flatMap(Content::parts).stream() + .flatMap(Collection::stream) + .map(Part::inlineData) + .filter(Optional::isPresent) + // Print some text to indicate that audio is returned. + .forEach(inlineData -> System.out.print("Some audio bytes in inline_data...")); + } + + private static void processGroundingMetadata(LiveServerContent content) { + // Print grounding metadata if present. + content.groundingMetadata().stream() + .flatMap(metadata -> metadata.groundingChunks().stream()) + .flatMap(Collection::stream) + .map(chunk -> chunk.web()) + .filter(Optional::isPresent) + .map(web -> web.get().uri()) + .filter(Optional::isPresent) + .forEach(uri -> System.out.println("\n\nGrounding URI: " + uri.get())); + } + private LiveTextToAudioTranscriptionAsync() {} } 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 203e126b5e7..92c1a11fd0f 100644 --- a/examples/src/main/java/com/google/genai/examples/LiveTextToTextGenerationAsync.java +++ b/examples/src/main/java/com/google/genai/examples/LiveTextToTextGenerationAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,10 +38,10 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.LiveTextToTextGenerationAsync" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; -import com.google.common.collect.ImmutableList; import com.google.genai.AsyncSession; import com.google.genai.Client; import com.google.genai.types.Content; @@ -73,26 +73,28 @@ public static void main(String[] args) { System.out.println("Using Gemini Developer API"); } + 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 = - LiveConnectConfig.builder() - .responseModalitiesFromKnown(ImmutableList.of(Modality.Known.TEXT)) - .build(); + LiveConnectConfig.builder().responseModalities(Modality.Known.TEXT).build(); CompletableFuture allDone = new CompletableFuture<>(); - String modelName; - if (client.vertexAI()) { - modelName = "gemini-2.0-flash-live-preview-04-09"; - } else { - modelName = "gemini-2.0-flash-live-001"; - } - - CompletableFuture futureSession = client.async.live.connect(modelName, config); + CompletableFuture futureSession = client.async.live.connect(modelId, config); futureSession .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 @@ -104,12 +106,16 @@ public static void main(String[] args) { // Receive messages from the live session. return session.receive(message -> printLiveServerMessage(message, allDone)); }) + // Wait for the allDone future to complete, which is signaled in + // printLiveServerMessage when the server is done sending messages. .thenCompose(unused -> allDone) + // Close the session. .thenCompose(unused -> session.close()); }) .join(); } + /** Wraps client message text. */ public static LiveSendClientContentParameters clientContentFromText(String text) { return LiveSendClientContentParameters.builder() .turnComplete(true) @@ -119,20 +125,19 @@ public static LiveSendClientContentParameters clientContentFromText(String text) public static void printLiveServerMessage( LiveServerMessage message, CompletableFuture allDone) { - if (message.serverContent().isPresent()) { - LiveServerContent content = message.serverContent().get(); - if (content.modelTurn().isPresent()) { - Content modelTurn = content.modelTurn().get(); - for (Part part : modelTurn.parts().orElse(ImmutableList.of())) { - if (part.text().isPresent()) { - System.out.print(part.text().get()); - } - } - } - if (content.turnComplete().orElse(false)) { - System.out.println(); - allDone.complete(null); - } + // Extract and print text from the model. + message + .serverContent() + .flatMap(LiveServerContent::modelTurn) + .flatMap(Content::parts) + .ifPresent(parts -> parts.forEach(part -> part.text().ifPresent(System.out::print))); + + // 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 d10595fd45c..0c51973a64e 100644 --- a/examples/src/main/java/com/google/genai/examples/ModelManagement.java +++ b/examples/src/main/java/com/google/genai/examples/ModelManagement.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -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 08965e3cdd9..a310cc28d68 100644 --- a/examples/src/main/java/com/google/genai/examples/ModelManagementAsync.java +++ b/examples/src/main/java/com/google/genai/examples/ModelManagementAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -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/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/RegisterFiles.java b/examples/src/main/java/com/google/genai/examples/RegisterFiles.java new file mode 100644 index 00000000000..5a1a80a853b --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/RegisterFiles.java @@ -0,0 +1,76 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.genai.examples; + +import com.google.auth.oauth2.GoogleCredentials; +import com.google.genai.Client; +import com.google.genai.types.Content; +import com.google.genai.types.File; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.Part; +import com.google.genai.types.RegisterFilesResponse; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +/** + * An example of how to use the registerFiles method to register GCS files with the Gemini Developer + * API. + */ +public final class RegisterFiles { + public static void main(String[] args) throws IOException { + // Instantiate the client. The client by default uses the Gemini Developer API. + Client client = new Client(); + + if (client.vertexAI()) { + System.out.println("registerFiles is only supported in the Gemini Developer client."); + System.exit(0); + } + + // GoogleCredentials.getApplicationDefault() will use application default credentials. + // Note: registerFiles is only supported by the Gemini Developer API (MLDev), not Vertex AI. + GoogleCredentials credentials = + GoogleCredentials.getApplicationDefault() + .createScoped( + Arrays.asList( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/devstorage.read_only")); + + List uris = Arrays.asList("gs://tensorflow_docs/image.jpg"); + + RegisterFilesResponse response = client.files.registerFiles(credentials, uris, null); + + List files = + response.files().orElseThrow(() -> new RuntimeException("No files returned")); + File file = files.get(0); + + System.out.println("Registered file: " + file.uri().get()); + + // Use the registered file in a generateContent call. + Content content = + Content.fromParts( + Part.fromText("can you summarize this file?"), + Part.fromUri(file.uri().get(), file.mimeType().get())); + + GenerateContentResponse genResponse = + client.models.generateContent("gemini-2.5-flash", content, null); + + System.out.println("Response: " + genResponse.text()); + } + + private RegisterFiles() {} +} 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 f4310e976cb..d21ecee4850 100644 --- a/examples/src/main/java/com/google/genai/examples/RequestLevelHttpOptions.java +++ b/examples/src/main/java/com/google/genai/examples/RequestLevelHttpOptions.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -38,6 +38,7 @@ *

mvn clean compile * *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.RequestLevelHttpOptions" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -46,10 +47,18 @@ 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) { + 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 @@ -66,14 +75,17 @@ 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 = - client.models.generateContent("gemini-2.0-flash-001", "Tell me the history of LLM", config); + client.models.generateContent(modelId, "Tell me the history of LLM", config); System.out.println("Response: " + response.text()); } 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 new file mode 100644 index 00000000000..05f323a6164 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/TuningJobs.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. + */ + +/** + * 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.TuningJobs" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.ListTuningJobsConfig; +import com.google.genai.types.TuningDataset; +import com.google.genai.types.TuningJob; + +/** An example of using the Unified Gen AI Java SDK to do operations on tuning jobs. */ +public final class TuningJobs { + + 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"); + // Create a tuning job. + TuningDataset tuningDataset = + TuningDataset.builder() + .gcsUri( + "gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl") + .build(); + TuningJob tuningJob1 = client.tunings.tune(modelId, tuningDataset, null); + System.out.println("Created tuning job: " + tuningJob1); + // Get the tuning job by name. + TuningJob tuningJob2 = client.tunings.get(tuningJob1.name().get(), null); + System.out.println("Get tuning job: " + tuningJob2); + + // Wait for the tuned model to be available. + String tunedModel = ""; + while (tunedModel.isEmpty()) { + System.out.println("Waiting for tuned model to be available"); + try { + Thread.sleep(10000); // Sleep for 10 seconds. + } catch (InterruptedException e) { + System.out.println("Thread was interrupted while sleeping."); + Thread.currentThread().interrupt(); + } + // Get the tuning job. + TuningJob fetchedTuningJob = client.tunings.get(tuningJob1.name().get(), null); + if (fetchedTuningJob.tunedModel().isPresent() + && fetchedTuningJob.tunedModel().get().model().isPresent()) { + tunedModel = fetchedTuningJob.tunedModel().get().model().get(); + } + } + System.out.println("Tuned model: " + tunedModel); + System.out.println(); + } else { + System.out.println("Using Gemini Developer API"); + } + + // List tuning jobs. + System.out.println("List tuning jobs resource names: "); + for (TuningJob t : + client.tunings.list(ListTuningJobsConfig.builder().pageSize(5).build()).page()) { + System.out.println(t.name().get()); + System.out.println(t.state().get()); + } + } + + private TuningJobs() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/TuningJobsAsync.java b/examples/src/main/java/com/google/genai/examples/TuningJobsAsync.java new file mode 100644 index 00000000000..442a062ba2a --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/TuningJobsAsync.java @@ -0,0 +1,163 @@ +/* + * 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.TuningJobsAsync" + * -Dexec.args="YOUR_MODEL_ID" + */ +package com.google.genai.examples; + +import com.google.genai.AsyncPager; +import com.google.genai.Client; +import com.google.genai.types.ListTuningJobsConfig; +import com.google.genai.types.TuningDataset; +import com.google.genai.types.TuningJob; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** An example of using the Unified Gen AI Java SDK to do async operations on tuning jobs. */ +public final class TuningJobsAsync { + + 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(); + ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); + + try { + if (client.vertexAI()) { + System.out.println("Using Vertex AI"); + // Create a tuning job. + TuningDataset tuningDataset = + TuningDataset.builder() + .gcsUri( + "gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl") + .build(); + CompletableFuture tuningJob1Future = + client.async.tunings.tune(modelId, tuningDataset, null); + tuningJob1Future + .thenCompose( + tuningJob -> { + System.out.println("Created tuning job: " + tuningJob.name().get()); + return pollUntilComplete(tuningJob.name().get(), client, scheduler); + }) + .thenAccept( + finalJob -> { + String tunedModel = finalJob.tunedModel().get().model().get(); + System.out.println("Tuned model: " + tunedModel); + }) + .join(); + System.out.println(); + } else { + System.out.println("Using Gemini Developer API"); + } + + // List tuning jobs. + CompletableFuture> asyncPagerFuture = + client.async.tunings.list(ListTuningJobsConfig.builder().pageSize(5).build()); + asyncPagerFuture + .thenCompose( + asyncPager -> { + System.out.println("List tuning jobs resource names: "); + return asyncPager.page(); + }) + .thenAccept( + page -> { + page.forEach( + job -> System.out.println(job.name().get() + "\n" + job.state().get())); + }) + .join(); + } finally { + scheduler.shutdown(); + } + } + + @SuppressWarnings("FutureReturnValueIgnored") + // Polls the tuning job status asynchronously until it is complete. + private static CompletableFuture pollUntilComplete( + String jobName, Client client, ScheduledExecutorService scheduler) { + + return client + .async + .tunings + .get(jobName, null) + .thenCompose( + job -> { + // Check if the model is ready. + if (job.tunedModel().isPresent() && job.tunedModel().get().model().isPresent()) { + return CompletableFuture.completedFuture(job); + } else { + // The job is not done. Schedule the next poll. + System.out.println( + "Waiting for tuned model to be available... Current state: " + + job.state().get()); + CompletableFuture result = new CompletableFuture<>(); + // Schedule the next call to this same method after a 10-second delay. + scheduler.schedule( + () -> + pollUntilComplete(jobName, client, scheduler) + .thenAccept(result::complete) + .exceptionally( + ex -> { + result.completeExceptionally(ex); + return null; + }), + 10, + TimeUnit.SECONDS); + return result; + } + }); + } + + private TuningJobsAsync() {} +} diff --git a/examples/src/main/java/com/google/genai/examples/TuningJobsWithEvaluationConfig.java b/examples/src/main/java/com/google/genai/examples/TuningJobsWithEvaluationConfig.java new file mode 100644 index 00000000000..5751172e116 --- /dev/null +++ b/examples/src/main/java/com/google/genai/examples/TuningJobsWithEvaluationConfig.java @@ -0,0 +1,164 @@ +/* + * 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.TuningJobs" + * -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.AutoraterConfig; +import com.google.genai.types.CreateTuningJobConfig; +import com.google.genai.types.EvaluationConfig; +import com.google.genai.types.GcsDestination; +import com.google.genai.types.ListTuningJobsConfig; +import com.google.genai.types.UnifiedMetric; +import com.google.genai.types.BleuSpec; +import com.google.genai.types.OutputConfig; +import com.google.genai.types.TuningDataset; +import com.google.genai.types.TuningJob; +import com.google.genai.types.TuningValidationDataset; +import com.google.genai.types.HttpOptions; + +/** + * An example of using the Unified Gen AI Java SDK to do operations on tuning jobs with an + * evaluation config. + */ +public final class TuningJobsWithEvaluationConfig { + + 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. + + // Tuning is currently only supported in v1beta1. + HttpOptions httpOptions = HttpOptions.builder().apiVersion("v1beta1").build(); + Client client = Client.builder().httpOptions(httpOptions).build(); + + if (client.vertexAI()) { + System.out.println("Using Vertex AI"); + // Create a tuning job. + TuningDataset tuningDataset = + TuningDataset.builder() + .gcsUri( + "gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl") + .build(); + + UnifiedMetric bleu = + UnifiedMetric.builder() + .bleuSpec(BleuSpec.builder().useEffectiveOrder(true).build()) + .build(); + + ImmutableList metrics = ImmutableList.of(bleu); + + EvaluationConfig evaluationConfig = + EvaluationConfig.builder() + .outputConfig( + OutputConfig.builder() + .gcsDestination( + GcsDestination.builder().outputUriPrefix("gs://YOUR_GCS_BUCKET/").build()) + .build()) + .autoraterConfig( + AutoraterConfig.builder().autoraterModel("test-model").samplingCount(1).build()) + .metrics(metrics) + .build(); + + CreateTuningJobConfig tuningConfig = + CreateTuningJobConfig.builder() + .epochCount(1) + .tunedModelDisplayName("tuning job with eval config") + .validationDataset( + TuningValidationDataset.builder() + .gcsUri( + "gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_validation_data.jsonl") + .build()) + .evaluationConfig(evaluationConfig) + .build(); + + TuningJob tuningJob1 = client.tunings.tune(modelId, tuningDataset, tuningConfig); + System.out.println("Created tuning job: " + tuningJob1); + + // Wait for the tuned model to be available. + String tunedModel = ""; + while (tunedModel.isEmpty()) { + System.out.println("Waiting for tuned model to be available"); + try { + Thread.sleep(10000); // Sleep for 10 seconds. + } catch (InterruptedException e) { + System.out.println("Thread was interrupted while sleeping."); + Thread.currentThread().interrupt(); + } + // Get the tuning job. + TuningJob fetchedTuningJob = client.tunings.get(tuningJob1.name().get(), null); + if (fetchedTuningJob.tunedModel().isPresent() + && fetchedTuningJob.tunedModel().get().model().isPresent()) { + tunedModel = fetchedTuningJob.tunedModel().get().model().get(); + } + } + System.out.println("Tuned model: " + tunedModel); + System.out.println(); + } else { + System.out.println("Gemini Developer API is not supported for this example."); + System.exit(0); + } + + // List tuning jobs. + System.out.println("List tuning jobs resource names: "); + for (TuningJob t : + client.tunings.list(ListTuningJobsConfig.builder().pageSize(5).build()).page()) { + System.out.println(t.name().get()); + System.out.println(t.state().get()); + } + } + + private TuningJobsWithEvaluationConfig() {} +} 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 96e9eea2c76..a7fa7393561 100644 --- a/examples/src/main/java/com/google/genai/examples/UpscaleImage.java +++ b/examples/src/main/java/com/google/genai/examples/UpscaleImage.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.UpscaleImage" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -47,6 +48,13 @@ /** An example of using the Unified Gen AI Java SDK to upscale an image. */ public final class UpscaleImage { public static void main(String[] args) { + 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 // 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 @@ -60,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: @@ -69,10 +78,14 @@ public static void main(String[] args) { UpscaleImageResponse upscaleImageResponse = client.models.upscaleImage( - "imagen-3.0-generate-001", + modelId, image, "x2", - UpscaleImageConfig.builder().outputMimeType("image/jpeg").build()); + UpscaleImageConfig.builder() + .outputMimeType("image/jpeg") + .enhanceInputImage(true) + .imagePreservationFactor(0.6f) + .build()); Image upscaledImage = upscaleImageResponse.generatedImages().get().get(0).image().get(); // Do something with upscaledImage. 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 b71f4d69ab3..df3e099c881 100644 --- a/examples/src/main/java/com/google/genai/examples/UpscaleImageAsync.java +++ b/examples/src/main/java/com/google/genai/examples/UpscaleImageAsync.java @@ -28,7 +28,7 @@ * *

export GOOGLE_GENAI_USE_VERTEXAI=true * - *

1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a + *

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 @@ -36,6 +36,7 @@ *

2. Compile the java package and run the sample code. * *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.UpscaleImageAsync" + * -Dexec.args="YOUR_MODEL_ID" */ package com.google.genai.examples; @@ -48,6 +49,13 @@ /** 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) { + 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 // 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 @@ -61,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: @@ -70,7 +79,7 @@ public static void main(String[] args) { CompletableFuture upscaleImageResponseFuture = client.async.models.upscaleImage( - "imagen-3.0-generate-001", + modelId, image, "x2", UpscaleImageConfig.builder().outputMimeType("image/jpeg").build()); diff --git a/pom.xml b/pom.xml index bfdf0548ae1..19345fb54fe 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.google.genai google-genai google-genai - 1.4.0-SNAPSHOT + 1.54.0-SNAPSHOT jar Java idiomatic SDK for the Gemini Developer APIs and Vertex AI APIs. @@ -47,14 +47,16 @@ 1.8 1.8 1.33.0 - 2.47.0 + 3.25.5 + 2.45.0 4.5.14 - 4.4.16 1.11.0 2.17.2 5.11.4 - 3.12.4 1.6.0 + 4.12.0 + src/main/java + src/test/java @@ -90,16 +92,8 @@ org.apache.httpcomponents httpclient ${apache.httpcomponents.httpclient.version} - - - org.apache.httpcomponents - httpcore - ${apache.httpcomponents.httpcore.version} - - - com.google.auto.value - auto-value - ${auto-value.version} + + true com.google.auto.value @@ -131,6 +125,16 @@ Java-WebSocket ${java-websocket.version} + + com.squareup.okhttp3 + okhttp + ${okhttp.version} + + + com.google.protobuf + protobuf-java + ${protobuf.version} + org.junit.jupiter @@ -150,19 +154,6 @@ ${junit.version} test - - org.junit.jupiter - junit-jupiter-params - ${junit.version} - test - - - - org.mockito - mockito-core - ${mockito.version} - test - org.jspecify @@ -170,14 +161,22 @@ 1.0.0 - com.github.tomakehurst - wiremock-jre8 - 2.35.0 - test + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + 1.9.10 + ${project.basedir}/${main.java.src.dir} + ${project.basedir}/${test.java.src.dir} + + + kr.motd.maven + os-maven-plugin + 1.7.1 + + @@ -201,6 +200,9 @@ ${auto-value.version} + + -parameters + @@ -208,20 +210,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 @@ -267,16 +276,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - 3.14.0 - - - -parameters - - - org.apache.maven.plugins maven-javadoc-plugin @@ -321,6 +320,7 @@ test report + check @@ -328,11 +328,236 @@ com/google/genai/types/AutoValue_*.class + com/google/genai/shaded/**/*.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.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + package + + shade + + + + + org.jetbrains.kotlin:kotlin-stdlib-jdk8 + org.jetbrains.kotlin:kotlin-stdlib + org.jetbrains.kotlin:kotlin-reflect + com.fasterxml.jackson.module:jackson-module-kotlin + + + + + + + + kotlin. + com.google.genai.shaded.kotlin. + + + com.fasterxml.jackson.module.kotlin. + com.google.genai.shaded.jackson.module.kotlin. + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.5.0 + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/protobuf/java + + + + jdk8-build + + [1.8,1.9) + + + + org.mockito + mockito-inline + 3.12.4 + test + + + + + + modern-jdk-build + + [11,) + + + + org.mockito + mockito-core + 5.12.0 + test + + + + + + native-tests + + + + org.apache.maven.plugins + maven-surefire-plugin + + @{argLine} -agentlib:native-image-agent=config-output-dir=target/native-image + + + + org.graalvm.buildtools + native-maven-plugin + 0.11.1 + true + + + --no-fallback + --verbose + + + + + + + + + private + + src/private/java + src/private/test/java + true + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + + add-public-test-source + generate-test-sources + + add-test-source + + + + ${project.basedir}/src/test/java + + + + + + + maven-compiler-plugin + + + **/HttpApiClientTest.java + **/GoogleCredentialsHttpClientTest.java + + + + + + + \ No newline at end of file diff --git a/release-please-config.json b/release-please-config.json index ce2b1c767ba..176e73c2c6f 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,17 +1,15 @@ { "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", - "release-type": "maven", "versioning": "always-bump-minor", "separate-pull-requests": true, "include-component-in-tag": false, - "initial-version": "0.2.0-SNAPSHOT", - "extra-files": ["README.md", "src/main/java/com/google/genai/ApiClient.java"], + "bump-minor-pre-major": false, + "bump-patch-for-minor-pre-major": false, "packages": { ".": { - "changelog-path": "CHANGELOG.md", - "release-type": "maven", - "bump-minor-pre-major": false, - "bump-patch-for-minor-pre-major": false + "release-type": "java-yoshi", + "extra-files": ["README.md", "src/main/java/com/google/genai/ApiClient.java"], + "changelog-path": "CHANGELOG.md" } } } \ No newline at end of file diff --git a/releases.txt b/releases.txt index a52927e3d87..d80ca429ea8 100644 --- a/releases.txt +++ b/releases.txt @@ -1,4 +1,4 @@ -Use this file when you need to force a patch release with release-please. -Edit line 4 below with the version for the release. +To trigger a manual patch release via release-please, edit the version on +line 4. -1.0.0 +1.50.1 diff --git a/run_interactions_examples.sh b/run_interactions_examples.sh new file mode 100755 index 00000000000..e4b84dd2256 --- /dev/null +++ b/run_interactions_examples.sh @@ -0,0 +1,67 @@ +#!/bin/bash +# Script to run Java GenAI SDK Interaction examples using Maven. + +ORIGINAL_DIR=$(pwd) + +declare -A FAILED_EXAMPLES + +# --- Install the package if needed --- +if [ -z "$(find target -name 'google-genai-*.jar')" ]; then + echo "Project JAR not found in target/. Running 'mvn install'..." + mvn install -Dclirr.skip=true +else + echo "Project JAR found. Skipping 'mvn install'." +fi + +cd examples +echo "Compiling the examples..." +mvn compile +if [ $? -ne 0 ]; then + echo "----------------------------------------" + echo "ERROR: Maven compilation failed. Exiting." + echo "----------------------------------------" + cd "$ORIGINAL_DIR" + exit 1 +fi + +declare -a TARGETS=() +for file in src/main/java/com/google/genai/examples/Interaction*.java; do + if [ -f "$file" ]; then + TARGETS+=("$(basename "$file" .java)") + fi +done + +if [ ${#TARGETS[@]} -eq 0 ]; then + echo "No interaction examples found matching Interaction*.java" + cd "$ORIGINAL_DIR" + exit 0 +fi + +for target in "${TARGETS[@]}"; do + echo "========================================" + echo "Running: $target" + echo "========================================" + + mvn exec:java -Dexec.mainClass="com.google.genai.examples.$target" + + if [ $? -ne 0 ]; then + echo "ERROR: $target failed." + FAILED_EXAMPLES["$target"]="Failed" + else + echo "SUCCESS: $target completed." + fi +done + +cd "$ORIGINAL_DIR" + +echo "========================================" +if [ ${#FAILED_EXAMPLES[@]} -eq 0 ]; then + echo "All interaction examples passed! ✅" + exit 0 +else + echo "The following examples failed: ❌" + for failed in "${!FAILED_EXAMPLES[@]}"; do + echo " - $failed" + done + exit 1 +fi diff --git a/src/main/java/com/google/genai/AfcUtil.java b/src/main/java/com/google/genai/AfcUtil.java index 9c888abe842..8ff11ce0ac8 100644 --- a/src/main/java/com/google/genai/AfcUtil.java +++ b/src/main/java/com/google/genai/AfcUtil.java @@ -38,7 +38,7 @@ final class AfcUtil { private static final Logger logger = Logger.getLogger(AfcUtil.class.getName()); private static final int DEFAULT_MAX_REMOTE_CALLS_AFC = 10; - static boolean hasCallableTool(ApiClient apiClient, GenerateContentConfig config) { + static boolean hasCallableTool(GenerateContentConfig config) { if (config == null) { return false; } @@ -53,13 +53,12 @@ static boolean hasCallableTool(ApiClient apiClient, GenerateContentConfig config return false; } - static GenerateContentConfig transformGenerateContentConfig( - ApiClient apiClient, GenerateContentConfig config) { + static GenerateContentConfig transformGenerateContentConfig(GenerateContentConfig config) { GenerateContentConfig transformedConfig; if (config != null && config.tools().isPresent() && !config.tools().get().isEmpty()) { ImmutableList transformedTools = config.tools().get().stream() - .map(tool -> Transformers.tTool(apiClient, tool)) + .map(tool -> Transformers.tTool(tool)) .collect(toImmutableList()); ObjectNode configNode = JsonSerializable.objectMapper.valueToTree(config); configNode.set("tools", JsonSerializable.objectMapper.valueToTree(transformedTools)); @@ -70,6 +69,26 @@ static GenerateContentConfig transformGenerateContentConfig( return transformedConfig; } + static ImmutableList findAfcIncompatibleToolIndexes(GenerateContentConfig config) { + if (config == null || !config.tools().isPresent() || config.tools().get().isEmpty()) { + return ImmutableList.of(); + } + List tools = config.tools().get(); + ImmutableList.Builder incompatibleToolsIndexesBuilder = ImmutableList.builder(); + + for (int i = 0; i < tools.size(); i++) { + Tool tool = tools.get(i); + if (tool.functionDeclarations().isPresent() && !tool.functionDeclarations().get().isEmpty()) { + incompatibleToolsIndexesBuilder.add(i); + } + if (tool.mcpServers().isPresent() && !tool.mcpServers().get().isEmpty()) { + incompatibleToolsIndexesBuilder.add(i); + } + } + + return incompatibleToolsIndexesBuilder.build(); + } + static ImmutableMap getFunctionMap(GenerateContentConfig config) { ImmutableMap.Builder functionMapBuilder = ImmutableMap.builder(); if (config != null && config.tools().isPresent() && !config.tools().get().isEmpty()) { @@ -201,28 +220,26 @@ private static Object getFunctionResponse( + argsFromModel); } Object argValueFromModel = argsFromModel.get(parameterName); - switch (argValueFromModel.getClass().getName()) { - case "java.lang.String": - argsListFromModel.add(argValueFromModel); - break; - case "java.lang.Integer": - argsListFromModel.add(Integer.parseInt(argValueFromModel.toString())); - break; - case "java.lang.Double": - argsListFromModel.add(Double.parseDouble(argValueFromModel.toString())); - break; - case "java.lang.Float": - argsListFromModel.add(Float.parseFloat(argValueFromModel.toString())); - break; - case "java.lang.Boolean": - argsListFromModel.add(Boolean.parseBoolean(argValueFromModel.toString())); - break; - default: - throw new IllegalArgumentException( - "The value type of the parameter \"" - + parameterName - + "\" is not supported. Supported types are String, Integer, Double, Float, and" - + " Boolean."); + String className = argValueFromModel.getClass().getName(); + + if (className.equals("java.lang.String")) { + argsListFromModel.add(argValueFromModel); + } else if (className.equals("java.lang.Integer")) { + argsListFromModel.add(Integer.parseInt(argValueFromModel.toString())); + } else if (className.equals("java.lang.Double")) { + argsListFromModel.add(Double.parseDouble(argValueFromModel.toString())); + } else if (className.equals("java.lang.Float")) { + argsListFromModel.add(Float.parseFloat(argValueFromModel.toString())); + } else if (className.equals("java.lang.Boolean")) { + argsListFromModel.add(Boolean.parseBoolean(argValueFromModel.toString())); + } else if (argValueFromModel instanceof List) { + argsListFromModel.add(argValueFromModel); + } else { + throw new IllegalArgumentException( + "The value type of the parameter \"" + + parameterName + + "\" is not supported. Supported types are String, Integer, Double, Float," + + " Boolean, and List."); } } diff --git a/src/main/java/com/google/genai/ApiClient.java b/src/main/java/com/google/genai/ApiClient.java index d6159c38884..67321d21c18 100644 --- a/src/main/java/com/google/genai/ApiClient.java +++ b/src/main/java/com/google/genai/ApiClient.java @@ -17,43 +17,82 @@ package com.google.genai; 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.api.core.InternalApi; 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.genai.errors.GenAiIOException; +import com.google.genai.types.ClientOptions; import com.google.genai.types.HttpOptions; +import com.google.genai.types.HttpRetryOptions; +import com.google.genai.types.ProxyOptions; +import com.google.genai.types.ProxyType; +import com.google.genai.types.ResourceScope.Known; import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.URI; +import java.net.URISyntaxException; +import java.time.Duration; +import java.util.HashMap; +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 org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; +import okhttp3.Credentials; +import okhttp3.Dispatcher; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; import org.jspecify.annotations.Nullable; /** Interface for an API client which issues HTTP requests to the GenAI APIs. */ -abstract class ApiClient { +@InternalApi +public abstract class ApiClient implements AutoCloseable { - private static final String SDK_VERSION = "1.3.0"; // x-version-update:google-genai:released + // {x-version-update-start:google-genai:released} + private static final String SDK_VERSION = "1.53.0"; + // {x-version-update-end:google-genai:released} private static final Logger logger = Logger.getLogger(ApiClient.class.getName()); - CloseableHttpClient httpClient; + private static final ImmutableSet METHODS_WITH_BODY = + ImmutableSet.of("POST", "PATCH", "PUT"); + + private static final ImmutableSet VALID_HTTP_METHODS = + ImmutableSet.builder().addAll(METHODS_WITH_BODY).add("GET").add("DELETE").build(); + + private static final ImmutableSet MULTI_REGIONAL_LOCATIONS = ImmutableSet.of("us", "eu"); + + private static Optional geminiBaseUrl = Optional.empty(); + private static Optional vertexBaseUrl = Optional.empty(); + + final OkHttpClient httpClient; + HttpOptions httpOptions; + final boolean vertexAI; + final Optional clientOptions; + final Optional customBaseUrl; // For Google AI APIs final Optional apiKey; // For Vertex AI APIs final Optional project; final Optional location; final Optional credentials; - HttpOptions httpOptions; - final boolean vertexAI; /** Constructs an ApiClient for Google AI APIs. */ - protected ApiClient(Optional apiKey, Optional customHttpOptions) { + protected ApiClient( + Optional apiKey, + Optional customHttpOptions, + Optional clientOptions) { checkNotNull(apiKey, "API Key cannot be null"); checkNotNull(customHttpOptions, "customHttpOptions cannot be null"); + checkNotNull(clientOptions, "clientOptions cannot be null"); try { this.apiKey = Optional.of(apiKey.orElse(getApiKeyFromEnv())); @@ -68,90 +107,429 @@ protected ApiClient(Optional apiKey, Optional customHttpOpt this.location = Optional.empty(); this.credentials = Optional.empty(); this.vertexAI = false; + this.clientOptions = clientOptions; + this.customBaseUrl = + customHttpOptions.flatMap(HttpOptions::baseUrl).map(url -> url.replaceAll("/$", "")); - this.httpOptions = defaultHttpOptions(/* vertexAI= */ false, this.location); + this.httpOptions = + defaultHttpOptions( + /* vertexAI= */ false, this.location, this.apiKey, this.customBaseUrl, Optional.empty()); if (customHttpOptions.isPresent()) { this.httpOptions = mergeHttpOptions(customHttpOptions.get()); } - this.httpClient = createHttpClient(httpOptions.timeout()); + this.httpClient = createHttpClient(httpOptions, clientOptions); } ApiClient( + Optional apiKey, Optional project, Optional location, Optional credentials, - Optional customHttpOptions) { + Optional customHttpOptions, + Optional clientOptions) { + checkNotNull(apiKey, "API Key cannot be null"); checkNotNull(project, "project cannot be null"); checkNotNull(location, "location cannot be null"); checkNotNull(credentials, "credentials cannot be null"); checkNotNull(customHttpOptions, "customHttpOptions cannot be null"); + checkNotNull(clientOptions, "clientOptions cannot be null"); - try { - this.project = Optional.of(project.orElse(System.getenv("GOOGLE_CLOUD_PROJECT"))); - } catch (NullPointerException e) { + ImmutableMap environmentVariables = defaultEnvironmentVariables(); + + // Retrieve implicitly set values from the environment. + String envApiKeyValue = getApiKeyFromEnv(); + String envProjectValue = environmentVariables.get("project"); + String envLocationValue = environmentVariables.get("location"); + + // Constructor arguments take priority over environment variables. + String apiKeyValue = apiKey.orElse(envApiKeyValue); + String projectValue = project.orElse(envProjectValue); + String locationValue = location.orElse(envLocationValue); + + // Has environment variable values. + boolean hasEnvApiKeyValue = envApiKeyValue != null && !envApiKeyValue.isEmpty(); + boolean hasEnvProjectValue = envProjectValue != null && !envProjectValue.isEmpty(); + boolean hasEnvLocationValue = envLocationValue != null && !envLocationValue.isEmpty(); + + // Constructor arguments. + boolean hasApiKey = apiKey != null && apiKey.isPresent(); + boolean hasCredentials = credentials != null && credentials.isPresent(); + boolean hasProject = project != null && project.isPresent(); + boolean hasLocation = location != null && location.isPresent(); + + Optional customBaseUrl = + customHttpOptions.flatMap(HttpOptions::baseUrl).map(url -> url.replaceAll("/$", "")); + + // Validate constructor arguments combinations. + if (hasProject && hasApiKey) { throw new IllegalArgumentException( - "Project must either be provided or set in the environment variable" - + " GOOGLE_CLOUD_PROJECT.", - e); + "For Vertex AI APIs, project and API key are mutually exclusive in the client" + + " initializer. Please provide only one of them."); } - if (this.project.get().isEmpty()) { - throw new IllegalArgumentException("Project must not be empty."); + + if (hasLocation && hasApiKey) { + throw new IllegalArgumentException( + "For Vertex AI APIs, location and API key are mutually exclusive in the client" + + " initializer. Please provide only one of them."); } - try { - this.location = Optional.of(location.orElse(System.getenv("GOOGLE_CLOUD_LOCATION"))); - } catch (NullPointerException e) { + if (hasCredentials && hasApiKey) { throw new IllegalArgumentException( - "Location must either be provided or set in the environment variable" - + " GOOGLE_CLOUD_LOCATION.", - e); + "For Vertex AI APIs, API key cannot be set together with credentials. Please provide" + + " only one of them."); + } + + // Handle when to use Vertex AI in express mode (api key). + // Explicit initializer arguments are already validated above. + if (hasCredentials && hasEnvApiKeyValue) { + logger.warning( + "Warning: The user provided Google Cloud credentials will take precedence over the API" + + " key from the environment variable."); + apiKeyValue = null; } - if (this.location.get().isEmpty()) { - throw new IllegalArgumentException("Location must not be empty."); + if (hasApiKey && (hasEnvProjectValue || hasEnvLocationValue)) { + // Explicit API key takes precedence over implicit project/location. + logger.warning( + "Warning: The user provided Vertex AI API key will take precedence over the" + + " project/location from the environment variables."); + projectValue = null; + locationValue = null; + } else if ((hasProject || hasLocation) && hasEnvApiKeyValue) { + // Explicit project/location takes precedence over implicit API key. + logger.warning( + "Warning: The user provided project/location will take precedence over the API key from" + + " the environment variable."); + apiKeyValue = null; + } else if ((hasEnvProjectValue || hasEnvLocationValue) && hasEnvApiKeyValue) { + // Implicit project/location takes precedence over implicit API key. + logger.warning( + "Warning: The project/location from the environment variables will take precedence over" + + " the API key from the environment variable."); + apiKeyValue = null; } - this.credentials = Optional.of(credentials.orElseGet(() -> defaultCredentials())); + if (locationValue == null && apiKeyValue == null && !customBaseUrl.isPresent()) { + locationValue = "global"; + } else if (locationValue == null + && apiKeyValue == null + && customBaseUrl.isPresent() + && customBaseUrl.get().endsWith(".googleapis.com")) { + locationValue = "global"; + } - this.httpOptions = defaultHttpOptions(/* vertexAI= */ true, this.location); + boolean hasSufficientAuth = + (projectValue != null && locationValue != null) || apiKeyValue != null; + if (!hasSufficientAuth && !customBaseUrl.isPresent()) { + throw new IllegalArgumentException( + "Authentication is not set up. Please provide either a project and location, or an API" + + " key, or a custom base URL."); + } + + boolean hasConstructorAuth = (hasProject && hasLocation) || hasApiKey; + HttpOptions.Builder initHttpOptionsBuilder = HttpOptions.builder(); + if (customBaseUrl.isPresent() && !hasConstructorAuth) { + initHttpOptionsBuilder.baseUrl(customBaseUrl.get()); + projectValue = null; + locationValue = null; + } else if (apiKeyValue != null + || (locationValue != null + && locationValue.equals("global") + && !customBaseUrl.isPresent())) { + initHttpOptionsBuilder.baseUrl("https://aiplatform.googleapis.com"); + } else if (locationValue != null + && MULTI_REGIONAL_LOCATIONS.contains(locationValue) + && !customBaseUrl.isPresent()) { + initHttpOptionsBuilder.baseUrl( + String.format("https://aiplatform.%s.rep.googleapis.com", locationValue)); + } else if (locationValue != null && !customBaseUrl.isPresent()) { + initHttpOptionsBuilder.baseUrl( + String.format("https://%s-aiplatform.googleapis.com", locationValue)); + } + + this.apiKey = Optional.ofNullable(apiKeyValue); + this.project = Optional.ofNullable(projectValue); + this.location = Optional.ofNullable(locationValue); + this.customBaseUrl = customBaseUrl; + + // Only set credentials if using project/location. + this.credentials = + !this.project.isPresent() + ? Optional.empty() + : Optional.of(credentials.orElseGet(() -> defaultCredentials())); + + this.clientOptions = clientOptions; + + this.httpOptions = + defaultHttpOptions( + /* vertexAI= */ true, + this.location, + this.apiKey, + this.customBaseUrl, + initHttpOptionsBuilder.build().baseUrl()); if (customHttpOptions.isPresent()) { this.httpOptions = mergeHttpOptions(customHttpOptions.get()); } - this.apiKey = Optional.empty(); this.vertexAI = true; - this.httpClient = createHttpClient(httpOptions.timeout()); + this.httpClient = createHttpClient(httpOptions, clientOptions); } - private String getApiKeyFromEnv() { - String googleApiKey = System.getenv("GOOGLE_API_KEY"); - if (googleApiKey != null && googleApiKey.isEmpty()) { - googleApiKey = null; + private OkHttpClient createHttpClient( + 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)); + + httpOptions.timeout().ifPresent(timeout -> builder.callTimeout(Duration.ofMillis(timeout))); + + HttpRetryOptions retryOptions = + httpOptions.retryOptions().orElse(HttpRetryOptions.builder().build()); + builder.addInterceptor(new RetryInterceptor(retryOptions)); + + clientOptions.ifPresent( + options -> { + Dispatcher dispatcher = new Dispatcher(); + options.maxConnections().ifPresent(dispatcher::setMaxRequests); + options.maxConnectionsPerHost().ifPresent(dispatcher::setMaxRequestsPerHost); + builder.dispatcher(dispatcher); + options + .proxyOptions() + .ifPresent( + proxyOptions -> { + applyProxyOptions(proxyOptions, builder); + }); + }); + + return builder.build(); + } + + /** Applies the proxy options to the OkHttpClient builder. */ + private void applyProxyOptions(ProxyOptions proxyOptions, OkHttpClient.Builder builder) { + final ProxyType proxyType = proxyOptions.type().orElse(new ProxyType("HTTP")); + final Proxy.Type type; + + switch (proxyType.knownEnum()) { + case SOCKS: + type = Proxy.Type.SOCKS; + break; + case HTTP: + type = Proxy.Type.HTTP; + break; + case DIRECT: + builder.proxy(Proxy.NO_PROXY); + return; + default: + throw new IllegalArgumentException("Unsupported proxy type: " + proxyType); } - String geminiApiKey = System.getenv("GEMINI_API_KEY"); - if (geminiApiKey != null && geminiApiKey.isEmpty()) { - geminiApiKey = null; + // Set the proxy for non-direct types. + String host = + proxyOptions + .host() + .orElseThrow( + () -> new IllegalArgumentException("Proxy host is required in the ProxyOptions.")); + int port = + proxyOptions + .port() + .orElseThrow( + () -> new IllegalArgumentException("Proxy port is required in the ProxyOptions.")); + + builder.proxy(new Proxy(type, new InetSocketAddress(host, port))); + + // Set the proxy authenticator if username and password are provided. + boolean userPresent = proxyOptions.username().isPresent(); + boolean passPresent = proxyOptions.password().isPresent(); + + if (userPresent != passPresent) { + throw new IllegalArgumentException( + "Proxy username and password must both be provided or not at all."); } - if (googleApiKey != null && geminiApiKey != null) { + if (userPresent && passPresent) { + final String credential = + Credentials.basic(proxyOptions.username().get(), proxyOptions.password().get()); + builder.proxyAuthenticator( + (route, response) -> { + if (response.request().header("Proxy-Authorization") != null) { + return null; + } + return response + .request() + .newBuilder() + .header("Proxy-Authorization", credential) + .build(); + }); + } + } + + /** Builds a HTTP request given the http method, path, and request json string. */ + @SuppressWarnings("unchecked") + protected Request buildRequest( + String httpMethod, + String path, + String requestJson, + Optional requestHttpOptions) { + String capitalizedHttpMethod = Ascii.toUpperCase(httpMethod); + HttpOptions mergedHttpOptions = mergeHttpOptions(requestHttpOptions.orElse(null)); + + boolean prependProjectLocation = + shouldPrependVertexProjectPath(capitalizedHttpMethod, path, mergedHttpOptions); + + if (prependProjectLocation) { + path = + String.format("projects/%s/locations/%s/", this.project.get(), this.location.get()) + + path; + } + + String requestUrl; + + String baseUrl = + mergedHttpOptions + .baseUrl() + .orElseThrow(() -> new IllegalStateException("baseUrl is required.")); + if (baseUrl.endsWith("/")) { + // Sometimes users set the base URL with a trailing slash, so we need to remove it. + baseUrl = baseUrl.substring(0, baseUrl.length() - 1); + } + String apiVersion = + mergedHttpOptions + .apiVersion() + .orElseThrow(() -> new IllegalStateException("apiVersion is required.")); + + if (apiVersion.isEmpty()) { + requestUrl = String.format("%s/%s", baseUrl, path); + } else { + requestUrl = String.format("%s/%s/%s", baseUrl, apiVersion, path); + } + + if (!VALID_HTTP_METHODS.contains(capitalizedHttpMethod)) { + 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( - "Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."); + "HttpOptions.extraBody is set, but the HTTP method does not support a request body. " + + "The extraBody will be ignored."); } - if (googleApiKey != null) { - return googleApiKey; + + Request.Builder requestBuilder = + new Request.Builder().url(requestUrl).method(capitalizedHttpMethod, body); + + requestHttpOptions.ifPresent( + httpOptions -> { + requestBuilder.tag(HttpOptions.class, httpOptions); + if (httpOptions.retryOptions().isPresent()) { + requestBuilder.tag(HttpRetryOptions.class, mergedHttpOptions.retryOptions().get()); + } + }); + + setHeaders(requestBuilder, mergedHttpOptions); + return requestBuilder.build(); + } + + /** Builds a HTTP request given the http method, url, and request bytes. */ + protected Request buildRequest( + String httpMethod, + String url, + byte[] requestBytes, + Optional requestHttpOptions) { + HttpOptions mergedHttpOptions = mergeHttpOptions(requestHttpOptions.orElse(null)); + + String finalUrl = url; + if (mergedHttpOptions.baseUrl().isPresent()) { + try { + URI originalUri = new URI(url); + URI baseUri = new URI(mergedHttpOptions.baseUrl().get()); + + String baseUriPath = baseUri.getRawPath() != null ? baseUri.getRawPath() : ""; + String originalUriPath = originalUri.getRawPath() != null ? originalUri.getRawPath() : ""; + + String combinedPath; + if (baseUriPath.endsWith("/") && originalUriPath.startsWith("/")) { + combinedPath = baseUriPath + originalUriPath.substring(1); + } else { + combinedPath = baseUriPath + originalUriPath; + } + + finalUrl = + new URI( + baseUri.getScheme(), + baseUri.getRawAuthority(), + combinedPath, + originalUri.getRawQuery(), + originalUri.getRawFragment()) + .toString(); + } catch (URISyntaxException e) { + logger.warning("Failed to rewrite upload URL with base URL: " + e.getMessage()); + } + } + + if (httpMethod.equalsIgnoreCase("POST")) { + RequestBody body = + RequestBody.create(requestBytes, MediaType.get("application/octet-stream")); + Request.Builder requestBuilder = new Request.Builder().url(finalUrl).post(body); + requestHttpOptions.ifPresent( + httpOptions -> { + if (httpOptions.retryOptions().isPresent()) { + requestBuilder.tag(HttpRetryOptions.class, mergedHttpOptions.retryOptions().get()); + } + }); + setHeaders(requestBuilder, mergedHttpOptions); + return requestBuilder.build(); + } else { + throw new IllegalArgumentException( + "The request method with bytes is only supported for POST. Unsupported HTTP method: " + + httpMethod); } - return geminiApiKey; } - private CloseableHttpClient createHttpClient(Optional timeout) { - if (!timeout.isPresent()) { - return HttpClients.createDefault(); + /** Sets the required headers (including auth) on the request object. */ + private void setHeaders(Request.Builder request, HttpOptions requestHttpOptions) { + for (Map.Entry header : + requestHttpOptions.headers().orElse(ImmutableMap.of()).entrySet()) { + request.header(header.getKey(), header.getValue()); + } + + if (apiKey.isPresent()) { + // Sets API key for Gemini Developer API or Vertex AI Express mode + request.header("x-goog-api-key", apiKey.get()); + } else if (credentials.isPresent()) { + GoogleCredentials cred = credentials.get(); + try { + cred.refreshIfExpired(); + } catch (IOException e) { + throw new GenAiIOException("Failed to refresh credentials.", e); + } + String accessToken = cred.getAccessToken().getTokenValue(); + request.header("Authorization", "Bearer " + accessToken); + + if (cred.getQuotaProjectId() != null) { + request.header("x-goog-user-project", cred.getQuotaProjectId()); + } + } else if (!customBaseUrl.isPresent()) { + throw new IllegalStateException("credentials is required"); } - RequestConfig config = - RequestConfig.custom() - .setConnectTimeout(timeout.get()) - .build(); - return HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } /** Sends a Http request given the http method, path, and request json string. */ @@ -162,6 +540,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. @@ -190,11 +582,67 @@ public boolean vertexAI() { return apiKey.orElse(null); } + /** Returns the custom base URL if provided. */ + public @Nullable String customBaseUrl() { + return customBaseUrl.orElse(null); + } + /** Returns the HttpClient for API calls. */ - CloseableHttpClient httpClient() { + public OkHttpClient httpClient() { return httpClient; } + /** Returns the GoogleCredentials for Vertex AI APIs. */ + public @Nullable GoogleCredentials credentials() { + return credentials.orElse(null); + } + + /** Returns the HTTP options for API calls. */ + public HttpOptions httpOptions() { + return httpOptions; + } + + /** + * 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); @@ -204,6 +652,36 @@ private Optional> getTimeoutHeader(HttpOptions httpOptionsTo return Optional.empty(); } + /** + * Merges two user agent values, handling a special case for vertex-genai-modules. + * + *

Example: + *

  • val1 = google-genai-sdk/1.42.0 gl-java/22.0.2 + *
  • val2 = vertex-genai-modules/1.2.3 + *
  • Result: google-genai-sdk/1.42.0+vertex-genai-modules/1.2.3 gl-java/22.0.2 + * + * @param val1 The first value. + * @param val2 The second value. + * @return The merged user agent value. + */ + private String mergeUserAgentValues(String val1, String val2) { + String extensionRegex = "^vertex-genai-modules/[^ ]+.*"; + boolean val1Matches = val1.matches(extensionRegex); + boolean val2Matches = val2.matches(extensionRegex); + + if (val1Matches || val2Matches) { + String extensionHeader = val1Matches ? val1 : val2; + String baseHeader = val1Matches ? val2 : val1; + + // Find google-genai-sdk/x.y.z in baseHeader + if (baseHeader.contains("google-genai-sdk/")) { + // $1 refers to the matched (google-genai-sdk/[^ ]+) group + return baseHeader.replaceFirst("(google-genai-sdk/[^ ]+)", "$1+" + extensionHeader); + } + } + return val1 + " " + val2; + } + /** * Merges the http options to the client's http options. * @@ -215,15 +693,14 @@ 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.baseUrlResourceScope().ifPresent(mergedHttpOptionsBuilder::baseUrlResourceScope); + 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( @@ -234,15 +711,31 @@ HttpOptions mergeHttpOptions(HttpOptions httpOptionsToApply) { .entrySet() .stream()), httpOptionsToApply.headers().orElse(ImmutableMap.of()).entrySet().stream()); - Map mergedHeaders = - headersStream.collect( - toImmutableMap(Map.Entry::getKey, Map.Entry::getValue, (val1, val2) -> val2)); - mergedHttpOptionsBuilder.headers(mergedHeaders); + final Map mergedHeaders = new HashMap<>(); + headersStream.forEach( + entry -> + mergedHeaders.merge( + entry.getKey(), + entry.getValue(), + (val1, val2) -> { + if (entry.getKey().equals("user-agent") + || entry.getKey().equals("x-goog-api-client")) { + return mergeUserAgentValues(val1, val2); + } + return val2; + })); + mergedHttpOptionsBuilder.headers(ImmutableMap.copyOf(mergedHeaders)); } + return mergedHttpOptionsBuilder.build(); } - static HttpOptions defaultHttpOptions(boolean vertexAI, Optional location) { + static HttpOptions defaultHttpOptions( + boolean vertexAI, + Optional location, + Optional apiKey, + Optional customBaseUrl, + Optional initBaseUrl) { ImmutableMap.Builder defaultHeaders = ImmutableMap.builder(); defaultHeaders.put("Content-Type", "application/json"); defaultHeaders.put("user-agent", libraryVersion()); @@ -251,23 +744,66 @@ static HttpOptions defaultHttpOptions(boolean vertexAI, Optional locatio HttpOptions.Builder defaultHttpOptionsBuilder = HttpOptions.builder().headers(defaultHeaders.build()); - if (vertexAI && location.isPresent()) { - defaultHttpOptionsBuilder - .baseUrl( - location.get().equalsIgnoreCase("global") - ? "https://aiplatform.googleapis.com" - : String.format("https://%s-aiplatform.googleapis.com", location.get())) - .apiVersion("v1beta1"); - } else if (vertexAI && !location.isPresent()) { - throw new IllegalArgumentException("Location must be provided for Vertex AI APIs."); + ImmutableMap defaultEnvironmentVariables = defaultEnvironmentVariables(); + if (vertexAI) { + defaultHttpOptionsBuilder.apiVersion("v1beta1"); + String defaultBaseUrl = + vertexBaseUrl.orElseGet(() -> defaultEnvironmentVariables.get("vertexBaseUrl")); + if (defaultBaseUrl != null) { + defaultHttpOptionsBuilder.baseUrl(defaultBaseUrl); + } else if (initBaseUrl.isPresent()) { + defaultHttpOptionsBuilder.baseUrl(initBaseUrl.get()); + } else if (customBaseUrl.isPresent() + && !customBaseUrl.get().endsWith(".googleapis.com") + && !(location.isPresent() || apiKey.isPresent())) { + defaultHttpOptionsBuilder.baseUrl(customBaseUrl.get()); + } else if (apiKey.isPresent() || location.get().equalsIgnoreCase("global")) { + defaultHttpOptionsBuilder.baseUrl("https://aiplatform.googleapis.com"); + } else if (MULTI_REGIONAL_LOCATIONS.contains(location.get())) { + defaultHttpOptionsBuilder.baseUrl( + String.format("https://aiplatform.%s.rep.googleapis.com", location.get())); + } else { + defaultHttpOptionsBuilder.baseUrl( + String.format("https://%s-aiplatform.googleapis.com", location.get())); + } } else { - defaultHttpOptionsBuilder - .baseUrl("https://generativelanguage.googleapis.com") - .apiVersion("v1beta"); + defaultHttpOptionsBuilder.apiVersion("v1beta"); + String defaultBaseUrl = + geminiBaseUrl.orElseGet(() -> defaultEnvironmentVariables.get("geminiBaseUrl")); + if (defaultBaseUrl != null) { + defaultHttpOptionsBuilder.baseUrl(defaultBaseUrl); + } else { + defaultHttpOptionsBuilder.baseUrl("https://generativelanguage.googleapis.com"); + } } + return defaultHttpOptionsBuilder.build(); } + boolean shouldPrependVertexProjectPath( + String httpMethod, String path, HttpOptions httpOptions) { + if (httpOptions.baseUrlResourceScope().isPresent() + && httpOptions.baseUrl().isPresent() + && httpOptions.baseUrlResourceScope().get().knownEnum() == Known.COLLECTION) { + return false; + } + if (this.apiKey.isPresent()) { + return false; + } + if (!this.vertexAI) { + return false; + } + if (path.startsWith("projects/")) { + return false; + } + // These paths are used by Vertex's models.get and models.list calls. For base models Vertex + // does not accept a project/location prefix (for tuned model the prefix is required). + if (httpMethod.equals("GET") && path.startsWith("publishers/google/models")) { + return false; + } + return true; + } + GoogleCredentials defaultCredentials() { try { return GoogleCredentials.getApplicationDefault() @@ -278,4 +814,97 @@ GoogleCredentials defaultCredentials() { e); } } + + /** Returns the API key from defaultEnvironmentVariables. */ + static String getApiKeyFromEnv() { + + ImmutableMap environmentVariables = defaultEnvironmentVariables(); + + String googleApiKey = environmentVariables.get("googleApiKey"); + if (googleApiKey != null && googleApiKey.isEmpty()) { + googleApiKey = null; + } + String geminiApiKey = environmentVariables.get("geminiApiKey"); + if (geminiApiKey != null && geminiApiKey.isEmpty()) { + geminiApiKey = null; + } + if (googleApiKey != null && geminiApiKey != null) { + logger.warning("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."); + } + if (googleApiKey != null) { + return googleApiKey; + } + return geminiApiKey; + } + + /** + * Returns the default environment variables for the client. Supported environment variables: + * + *
      + *
    • googleApiKey -> GOOGLE_API_KEY environment variable. + *
    • geminiApiKey -> GEMINI_API_KEY environment variable. + *
    • project -> GOOGLE_CLOUD_PROJECT: Project ID for Vertex AI APIs. + *
    • location -> GOOGLE_CLOUD_LOCATION: Location for Vertex AI APIs. + *
    • vertexAI -> GOOGLE_GENAI_USE_VERTEXAI: Whether to use Vertex AI APIs(true or false). + *
    • geminiBaseUrl -> GOOGLE_GEMINI_BASE_URL: Base URL for Gemini APIs. + *
    • vertexBaseUrl -> GOOGLE_VERTEX_BASE_URL: Base URL for Vertex AI APIs. + *
    + */ + public static ImmutableMap defaultEnvironmentVariables() { + ImmutableMap.Builder mapBuilder = ImmutableMap.builder(); + String value; + value = System.getenv("GOOGLE_API_KEY"); + if (value != null && !value.isEmpty()) { + mapBuilder.put("googleApiKey", value); + } + value = System.getenv("GEMINI_API_KEY"); + if (value != null && !value.isEmpty()) { + mapBuilder.put("geminiApiKey", value); + } + value = System.getenv("GOOGLE_CLOUD_PROJECT"); + if (value != null && !value.isEmpty()) { + mapBuilder.put("project", value); + } + value = System.getenv("GOOGLE_CLOUD_LOCATION"); + if (value != null && !value.isEmpty()) { + mapBuilder.put("location", value); + } + value = System.getenv("GOOGLE_GENAI_USE_VERTEXAI"); + if (value != null && !value.isEmpty()) { + mapBuilder.put("vertexAI", value); + } + value = System.getenv("GOOGLE_GENAI_USE_ENTERPRISE"); + if (value != null && !value.isEmpty()) { + mapBuilder.put("enterprise", value); + } + value = System.getenv("GOOGLE_GEMINI_BASE_URL"); + if (value != null && !value.isEmpty()) { + mapBuilder.put("geminiBaseUrl", value); + } + value = System.getenv("GOOGLE_VERTEX_BASE_URL"); + if (value != null && !value.isEmpty()) { + mapBuilder.put("vertexBaseUrl", value); + } + return mapBuilder.buildOrThrow(); + } + + /** Overrides the base URLs for the Gemini API and/or Vertex AI API. */ + public static void setDefaultBaseUrls( + Optional geminiBaseUrl, Optional vertexBaseUrl) { + ApiClient.geminiBaseUrl = geminiBaseUrl; + ApiClient.vertexBaseUrl = vertexBaseUrl; + } + + @Override + public void close() { + try { + httpClient().dispatcher().executorService().shutdown(); + httpClient().connectionPool().evictAll(); + if (httpClient().cache() != null) { + httpClient().cache().close(); + } + } catch (IOException e) { + throw new GenAiIOException("Failed to close the client.", e); + } + } } diff --git a/src/main/java/com/google/genai/ApiResponse.java b/src/main/java/com/google/genai/ApiResponse.java index dce8fe06c93..4de19149336 100644 --- a/src/main/java/com/google/genai/ApiResponse.java +++ b/src/main/java/com/google/genai/ApiResponse.java @@ -16,15 +16,18 @@ package com.google.genai; -import org.apache.http.Header; -import org.apache.http.HttpEntity; +import com.google.api.core.InternalApi; +import okhttp3.Headers; +import okhttp3.ResponseBody; /** The API response contains a response to a call to the GenAI APIs. */ -abstract class ApiResponse implements AutoCloseable { - /** Gets the HttpEntity. */ - public abstract HttpEntity getEntity(); +@InternalApi +public abstract class ApiResponse implements AutoCloseable { + /** Gets the ResponseBody. */ + public abstract ResponseBody getBody(); - public abstract Header[] getHeaders(); + /** Returns all of the headers from the response. */ + public abstract Headers getHeaders(); @Override public abstract void close(); diff --git a/src/main/java/com/google/genai/AsyncBatches.java b/src/main/java/com/google/genai/AsyncBatches.java new file mode 100644 index 00000000000..071704c5887 --- /dev/null +++ b/src/main/java/com/google/genai/AsyncBatches.java @@ -0,0 +1,257 @@ +/* + * 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.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. + * + * @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 Gemini Enterprise Agent Platform 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 CompletableFuture get(String name, GetBatchJobConfig 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); + } + }); + } + + /** + * Asynchronously 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 CompletableFuture cancel(String name, CancelBatchJobConfig 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); + } + }); + } + + /** + * Asynchronously 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 Gemini Enterprise Agent Platform client. Or "batches/abc" using the + * Gemini Developer AI client. + * @param config A {@link DeleteBatchJobConfig} for configuring the delete request. + */ + public CompletableFuture delete(String name, DeleteBatchJobConfig 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); + } + }); + } + + /** + * Asynchronously makes an API request to list the available batch jobs. + * + * @param config A {@link ListBatchJobsConfig} for configuring the list request. + * @return A CompletableFuture that resolves to a {@link AsyncPager}. The AsyncPager has a + * `forEach` method that can be used to asynchronously process items in the page and + * automatically query the next page once the current page is exhausted. + */ + @SuppressWarnings("PatternMatchingInstanceof") + public CompletableFuture> list(ListBatchJobsConfig config) { + if (config == null) { + config = ListBatchJobsConfig.builder().build(); + } + ListBatchJobsConfig finalConfig = config; + Function> request = + requestConfig -> { + if (!(requestConfig instanceof ListBatchJobsConfig)) { + throw new GenAiIOException( + "Internal error: Pager expected ListBatchJobsConfig but received " + + requestConfig.getClass().getName()); + } + return this.privateList((ListBatchJobsConfig) requestConfig) + .thenApply(JsonSerializable::toJsonNode); + }; + return CompletableFuture.supplyAsync( + () -> + new AsyncPager( + Pager.PagedItem.BATCH_JOBS, + request, + (ObjectNode) JsonSerializable.toJsonNode(finalConfig), + request.apply(finalConfig))); + } + + /** + * Asynchronously creates a batch job. + * + * @param model the name of the GenAI model to use for batch generation. + * @param src The {@link BatchJobSource} of the batch job. + * @param config The configuration {@link CreateBatchJobConfig} for the batch job. + * @return A future that resolves to the batch job. + */ + public CompletableFuture create( + String model, BatchJobSource src, CreateBatchJobConfig config) { + if (this.apiClient.vertexAI()) { + if (src.inlinedRequests().isPresent()) { + throw new GenAiIOException( + "inlinedRequests is not supported for Gemini Enterprise Agent Platform (previously" + + " known as Vertex AI)."); + } + if (src.fileName().isPresent()) { + throw new GenAiIOException( + "fileName is not supported for Gemini Enterprise Agent Platform (previously known as" + + " Vertex AI)."); + } + int count = 0; + if (src.gcsUri().isPresent()) { + count++; + } + if (src.bigqueryUri().isPresent()) { + count++; + } + if (src.vertexDatasetName().isPresent()) { + count++; + } + if (count > 1) { + throw new GenAiIOException( + "Only one of gcsUri, bigqueryUri, and vertexDatasetName can be set."); + } + if (count == 0) { + throw new GenAiIOException("One of gcsUri, bigqueryUri, or vertexDatasetName 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( + "Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support" + + " batches.createEmbeddings."); + } + return this.privateCreateEmbeddings(model, src, config); + } +} diff --git a/src/main/java/com/google/genai/AsyncCaches.java b/src/main/java/com/google/genai/AsyncCaches.java index 6061214bff9..7fdb067aca5 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,14 +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); } @@ -46,7 +52,16 @@ 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); + } + }); } /** @@ -57,7 +72,16 @@ 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); + } + }); } /** @@ -68,7 +92,50 @@ 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); + } + }); + } + + /** + * Asynchronously 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 CompletableFuture update(String name, UpdateCachedContentConfig 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); + } + }); } /** @@ -81,6 +148,10 @@ public CompletableFuture delete( */ @SuppressWarnings("PatternMatchingInstanceof") public CompletableFuture> list(ListCachedContentsConfig config) { + if (config == null) { + config = ListCachedContentsConfig.builder().build(); + } + ListCachedContentsConfig finalConfig = config; Function> request = requestConfig -> { if (!(requestConfig instanceof ListCachedContentsConfig)) { @@ -88,17 +159,15 @@ 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( () -> - new AsyncPager<>( + new AsyncPager( Pager.PagedItem.CACHED_CONTENTS, request, - (ObjectNode) JsonSerializable.toJsonNode(config), - request.apply(config))); + (ObjectNode) JsonSerializable.toJsonNode(finalConfig), + request.apply(finalConfig))); } } diff --git a/src/main/java/com/google/genai/AsyncDocuments.java b/src/main/java/com/google/genai/AsyncDocuments.java new file mode 100644 index 00000000000..fbc2917edf1 --- /dev/null +++ b/src/main/java/com/google/genai/AsyncDocuments.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. + */ + +// Auto-generated code. Do not edit. + +package com.google.genai; + +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.DeleteDocumentConfig; +import com.google.genai.types.Document; +import com.google.genai.types.GetDocumentConfig; +import com.google.genai.types.ListDocumentsConfig; +import com.google.genai.types.ListDocumentsResponse; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; + +/** Async module of {@link Documents} */ +public final class AsyncDocuments { + + Documents documents; + ApiClient apiClient; + + public AsyncDocuments(ApiClient apiClient) { + this.apiClient = apiClient; + this.documents = new Documents(apiClient); + } + + public CompletableFuture get(String name, GetDocumentConfig config) { + + BuiltRequest builtRequest = documents.buildRequestForGet(name, config); + return this.apiClient + .asyncRequest("get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return documents.processResponseForGet(res, config); + } + }); + } + + public CompletableFuture delete(String name, DeleteDocumentConfig config) { + + BuiltRequest builtRequest = documents.buildRequestForDelete(name, config); + return this.apiClient + .asyncRequest( + "delete", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenAccept( + response -> { + try (ApiResponse res = response) {} + }); + } + + CompletableFuture privateList(String parent, ListDocumentsConfig config) { + + BuiltRequest builtRequest = documents.buildRequestForPrivateList(parent, config); + return this.apiClient + .asyncRequest("get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return documents.processResponseForPrivateList(res, config); + } + }); + } + + /** + * Asynchronously makes an API request to list the available documents. + * + * @param parent The name of the RagStore containing the Documents. + * @param config A {@link ListDocumentsConfig} for configuring the list request. + * @return A CompletableFuture that resolves to a {@link AsyncPager}. The AsyncPager has a + * `forEach` method that can be used to asynchronously process items in the page and + * automatically query the next page once the current page is exhausted. + */ + @SuppressWarnings("PatternMatchingInstanceof") + public CompletableFuture> list(String parent, ListDocumentsConfig config) { + if (config == null) { + config = ListDocumentsConfig.builder().build(); + } + ListDocumentsConfig finalConfig = config; + Function> request = + requestConfig -> { + if (!(requestConfig instanceof ListDocumentsConfig)) { + throw new GenAiIOException( + "Internal error: Pager expected ListDocumentsConfig but received " + + requestConfig.getClass().getName()); + } + return this.privateList(parent, (ListDocumentsConfig) requestConfig) + .thenApply(JsonSerializable::toJsonNode); + }; + return CompletableFuture.supplyAsync( + () -> + new AsyncPager( + Pager.PagedItem.DOCUMENTS, + request, + (ObjectNode) JsonSerializable.toJsonNode(finalConfig), + request.apply(finalConfig))); + } +} diff --git a/src/main/java/com/google/genai/AsyncFileSearchStores.java b/src/main/java/com/google/genai/AsyncFileSearchStores.java new file mode 100644 index 00000000000..315caabf68f --- /dev/null +++ b/src/main/java/com/google/genai/AsyncFileSearchStores.java @@ -0,0 +1,377 @@ +/* + * 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.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.CreateFileSearchStoreConfig; +import com.google.genai.types.DeleteFileSearchStoreConfig; +import com.google.genai.types.DownloadMediaConfig; +import com.google.genai.types.FileSearchStore; +import com.google.genai.types.GetFileSearchStoreConfig; +import com.google.genai.types.HttpOptions; +import com.google.genai.types.HttpResponse; +import com.google.genai.types.ImportFileConfig; +import com.google.genai.types.ImportFileOperation; +import com.google.genai.types.ListFileSearchStoresConfig; +import com.google.genai.types.ListFileSearchStoresResponse; +import com.google.genai.types.UploadToFileSearchStoreConfig; +import com.google.genai.types.UploadToFileSearchStoreOperation; +import com.google.genai.types.UploadToFileSearchStoreResumableResponse; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; + +/** Async module of {@link FileSearchStores} */ +public final class AsyncFileSearchStores { + public final AsyncDocuments documents; + + FileSearchStores fileSearchStores; + ApiClient apiClient; + private final UploadClient uploadClient; + + public AsyncFileSearchStores(ApiClient apiClient) { + this.apiClient = apiClient; + this.fileSearchStores = new FileSearchStores(apiClient); + this.uploadClient = new UploadClient(apiClient); + this.documents = new AsyncDocuments(apiClient); + } + + public CompletableFuture create(CreateFileSearchStoreConfig config) { + + BuiltRequest builtRequest = fileSearchStores.buildRequestForCreate(config); + return this.apiClient + .asyncRequest("post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return fileSearchStores.processResponseForCreate(res, config); + } + }); + } + + public CompletableFuture get(String name, GetFileSearchStoreConfig config) { + + BuiltRequest builtRequest = fileSearchStores.buildRequestForGet(name, config); + return this.apiClient + .asyncRequest("get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return fileSearchStores.processResponseForGet(res, config); + } + }); + } + + public CompletableFuture delete(String name, DeleteFileSearchStoreConfig config) { + + BuiltRequest builtRequest = fileSearchStores.buildRequestForDelete(name, config); + return this.apiClient + .asyncRequest( + "delete", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenAccept( + response -> { + try (ApiResponse res = response) {} + }); + } + + CompletableFuture privateList(ListFileSearchStoresConfig config) { + + BuiltRequest builtRequest = fileSearchStores.buildRequestForPrivateList(config); + return this.apiClient + .asyncRequest("get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return fileSearchStores.processResponseForPrivateList(res, config); + } + }); + } + + CompletableFuture privateUploadToFileSearchStore( + String fileSearchStoreName, UploadToFileSearchStoreConfig config) { + + BuiltRequest builtRequest = + fileSearchStores.buildRequestForPrivateUploadToFileSearchStore(fileSearchStoreName, config); + return this.apiClient + .asyncRequest("post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return fileSearchStores.processResponseForPrivateUploadToFileSearchStore( + res, config); + } + }); + } + + public CompletableFuture importFile( + String fileSearchStoreName, String fileName, ImportFileConfig config) { + + BuiltRequest builtRequest = + fileSearchStores.buildRequestForImportFile(fileSearchStoreName, fileName, config); + return this.apiClient + .asyncRequest("post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return fileSearchStores.processResponseForImportFile(res, config); + } + }); + } + + /** + * Asynchronously makes an API request to list the available file search stores. + * + * @param config A {@link ListFileSearchStoresConfig} for configuring the list request. + * @return A CompletableFuture that resolves to a {@link AsyncPager}. The AsyncPager has a + * `forEach` method that can be used to asynchronously process items in the page and + * automatically query the next page once the current page is exhausted. + */ + @SuppressWarnings("PatternMatchingInstanceof") + public CompletableFuture> list(ListFileSearchStoresConfig config) { + if (config == null) { + config = ListFileSearchStoresConfig.builder().build(); + } + ListFileSearchStoresConfig finalConfig = config; + Function> request = + requestConfig -> { + if (!(requestConfig instanceof ListFileSearchStoresConfig)) { + throw new GenAiIOException( + "Internal error: Pager expected ListFileSearchStoresConfig but received " + + requestConfig.getClass().getName()); + } + return this.privateList((ListFileSearchStoresConfig) requestConfig) + .thenApply(JsonSerializable::toJsonNode); + }; + return CompletableFuture.supplyAsync( + () -> + new AsyncPager( + Pager.PagedItem.FILE_SEARCH_STORES, + request, + (ObjectNode) JsonSerializable.toJsonNode(finalConfig), + request.apply(finalConfig))); + } + + private CompletableFuture getUploadUrl( + String fileSearchStoreName, + UploadToFileSearchStoreConfig config, + Optional mimeType, + Optional fileName, + long size) { + Optional mimeTypeToUse = + mimeType.isPresent() + ? mimeType + : Optional.ofNullable(config).flatMap(UploadToFileSearchStoreConfig::mimeType); + Optional userHttpOptions = + Optional.ofNullable(config).flatMap(UploadToFileSearchStoreConfig::httpOptions); + HttpOptions httpOptions = + UploadClient.buildResumableUploadHttpOptions( + userHttpOptions, mimeTypeToUse, fileName, size); + return privateUploadToFileSearchStore( + fileSearchStoreName, + UploadToFileSearchStoreConfig.builder() + .httpOptions(httpOptions) + .shouldReturnHttpResponse(true) + .build()) + .thenApply( + response -> + response + .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 upload to file search store. Upload URL was not returned" + + " in the resumable response."))); + } + + /** + * Uploads a file to the file search store. + * + * @param fileSearchStoreName The name of the file search store to upload to. + * @param file The file to upload. + * @param config The configuration for the upload. + * @return The long running operation of uploading. + */ + public CompletableFuture uploadToFileSearchStore( + String fileSearchStoreName, java.io.File file, UploadToFileSearchStoreConfig config) { + long size = file.length(); + String fileName = file.getName(); + Optional mimeType; + try { + String probedMimeType = java.nio.file.Files.probeContentType(file.toPath()); + mimeType = Optional.ofNullable(probedMimeType); + } catch (IOException e) { + mimeType = Optional.empty(); + } + return getUploadUrl(fileSearchStoreName, config, mimeType, Optional.of(fileName), size) + .thenCompose( + uploadUrl -> + CompletableFuture.supplyAsync( + () -> { + try (InputStream inputStream = new FileInputStream(file)) { + Optional httpOptions = + config != null ? config.httpOptions() : Optional.empty(); + return uploadClient.upload(uploadUrl, inputStream, size, httpOptions); + } catch (IOException e) { + throw new GenAiIOException("Failed to upload file.", e); + } + })) + .thenApply(FileSearchStores::operationFromResponse); + } + + /** + * Uploads a file in bytes format to the file search store. + * + * @param fileSearchStoreName The name of the file search store to upload to. + * @param bytes The bytes of the file to upload. + * @param config The configuration for the upload. + * @return The long running operation of uploading. + */ + public CompletableFuture uploadToFileSearchStore( + String fileSearchStoreName, byte[] bytes, UploadToFileSearchStoreConfig config) { + return getUploadUrl( + fileSearchStoreName, + config, + Optional.empty(), + Optional.empty(), + bytes.length) + .thenCompose( + uploadUrl -> + CompletableFuture.supplyAsync( + () -> { + Optional httpOptions = + config != null ? config.httpOptions() : Optional.empty(); + return uploadClient.upload(uploadUrl, bytes, httpOptions); + })) + .thenApply(FileSearchStores::operationFromResponse); + } + + /** + * Uploads a file as input stream to the API. + * + * @param fileSearchStoreName The name of the file search store to upload to. + * @param inputStream The input stream of the file to upload. + * @param size The size of the file to upload. + * @param config The configuration for the upload. + * @return The uploaded file. + */ + public CompletableFuture uploadToFileSearchStore( + String fileSearchStoreName, + InputStream inputStream, + long size, + UploadToFileSearchStoreConfig config) { + return getUploadUrl( + fileSearchStoreName, config, Optional.empty(), Optional.empty(), size) + .thenCompose( + uploadUrl -> + CompletableFuture.supplyAsync( + () -> { + Optional httpOptions = + config != null ? config.httpOptions() : Optional.empty(); + return uploadClient.upload(uploadUrl, inputStream, size, httpOptions); + })) + .thenApply(FileSearchStores::operationFromResponse); + } + + /** + * Uploads a file to the API. + * + * @param fileSearchStoreName The name of the file search store to upload to. + * @param filePath The path of the file to upload. + * @param config The configuration for the upload. + * @return The uploaded file. + */ + public CompletableFuture uploadToFileSearchStore( + String fileSearchStoreName, String filePath, UploadToFileSearchStoreConfig config) { + java.io.File file = new java.io.File(filePath); + return uploadToFileSearchStore(fileSearchStoreName, file, config); + } + + /** + * Downloads media using a Media ID or URI. This method is only supported in the Gemini Developer + * client. + * + * @param uri The URI or Media ID of the blob. + * @param config Optional configuration for the download. + * @return A CompletableFuture that resolves to the blob data as a byte array. + */ + public CompletableFuture downloadMedia(String uri, DownloadMediaConfig config) { + if (this.apiClient.vertexAI()) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally( + new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client.")); + return future; + } + java.util.Objects.requireNonNull(uri, "uri cannot be null"); + + return CompletableFuture.supplyAsync( + () -> { + java.net.URI parsedUri; + try { + parsedUri = new java.net.URI(uri); + } catch (java.net.URISyntaxException e) { + throw new IllegalArgumentException("Invalid uri format: " + uri, e); + } + + String path = parsedUri.getPath(); + if (path != null && path.startsWith("/")) { + path = path.substring(1); + } + + if (path == null) { + throw new IllegalArgumentException("Invalid uri format (no path): " + uri); + } + + if (!path.contains("/media/")) { + throw new IllegalArgumentException( + "Invalid uri format: " + uri + ". Expected to contain /media/"); + } + + String requestPath = path + "?alt=media"; + + Optional httpOptions = Optional.empty(); + if (config != null) { + httpOptions = config.httpOptions(); + } + + ApiResponse response = this.apiClient.request("get", requestPath, "", httpOptions); + try { + return response.getBody().bytes(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read blob content.", e); + } + }); + } +} diff --git a/src/main/java/com/google/genai/AsyncFiles.java b/src/main/java/com/google/genai/AsyncFiles.java index 4070a1cfcc9..96b84bafaee 100644 --- a/src/main/java/com/google/genai/AsyncFiles.java +++ b/src/main/java/com/google/genai/AsyncFiles.java @@ -18,9 +18,15 @@ package com.google.genai; +import static com.google.common.base.Preconditions.checkNotNull; + import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.auth.oauth2.GoogleCredentials; +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,20 +34,53 @@ 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.RegisterFilesConfig; +import com.google.genai.types.RegisterFilesResponse; import com.google.genai.types.UploadFileConfig; import com.google.genai.types.Video; import java.io.InputStream; +import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Function; /** 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); } + 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 +89,16 @@ 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 +109,89 @@ 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); + } + }); + } + + CompletableFuture privateRegisterFiles( + List uris, RegisterFilesConfig config) { + + BuiltRequest builtRequest = files.buildRequestForPrivateRegisterFiles(uris, config); + return this.apiClient + .asyncRequest("post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return files.processResponseForPrivateRegisterFiles(res, config); + } + }); + } + + /** + * Asynchronously makes an API request to list the available files. + * + * @param config A {@link ListFilesConfig} for configuring the list request. + * @return A CompletableFuture that resolves to a {@link AsyncPager}. The AsyncPager has a + * `forEach` method that can be used to asynchronously process items in the page and + * automatically query the next page once the current page is exhausted. + */ + @SuppressWarnings("PatternMatchingInstanceof") + public CompletableFuture> list(ListFilesConfig config) { + if (config == null) { + config = ListFilesConfig.builder().build(); + } + ListFilesConfig finalConfig = config; + Function> request = + requestConfig -> { + if (!(requestConfig instanceof ListFilesConfig)) { + throw new GenAiIOException( + "Internal error: Pager expected ListFilesConfig but received " + + requestConfig.getClass().getName()); + } + return this.privateList((ListFilesConfig) requestConfig) + .thenApply(JsonSerializable::toJsonNode); + }; + return CompletableFuture.supplyAsync( + () -> + new AsyncPager( + Pager.PagedItem.FILES, + request, + (ObjectNode) JsonSerializable.toJsonNode(finalConfig), + request.apply(finalConfig))); + } + + /** + * Asynchronously registers Google Cloud Storage files for use with the API. + * + * @param credentials The Google Cloud credentials to use for registering the files. + * @param uris The list of GCS URIs to register. + * @param config Optional configuration for the registration request. + * @return A future that resolves to the response containing the registered files. + */ + public CompletableFuture registerFiles( + GoogleCredentials credentials, List uris, RegisterFilesConfig config) { + if (this.apiClient.vertexAI()) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally( + new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client.")); + return future; + } + checkNotNull(credentials, "credentials cannot be null"); + checkNotNull(uris, "uris cannot be null"); + + return CompletableFuture.supplyAsync( + () -> files.internalPrepareRegisterFilesConfig(credentials, config)) + .thenCompose(updatedConfig -> privateRegisterFiles(uris, updatedConfig)); } /** @@ -160,34 +290,4 @@ public CompletableFuture download( File file, String downloadPath, DownloadFileConfig config) { return CompletableFuture.runAsync(() -> files.download(file, downloadPath, config)); } - - /** - * Asynchronously makes an API request to list the available files. - * - * @param config A {@link ListFilesConfig} for configuring the list request. - * @return A CompletableFuture that resolves to a {@link AsyncPager}. The AsyncPager has a - * `forEach` method that can be used to asynchronously process items in the page and - * automatically query the next page once the current page is exhausted. - */ - @SuppressWarnings("PatternMatchingInstanceof") - public CompletableFuture> list(ListFilesConfig config) { - Function> request = - requestConfig -> { - if (!(requestConfig instanceof ListFilesConfig)) { - throw new GenAiIOException( - "Internal error: Pager expected ListFilesConfig but received " - + requestConfig.getClass().getName()); - } - return CompletableFuture.supplyAsync( - () -> - JsonSerializable.toJsonNode(files.privateList((ListFilesConfig) requestConfig))); - }; - return CompletableFuture.supplyAsync( - () -> - new AsyncPager<>( - Pager.PagedItem.FILES, - request, - (ObjectNode) JsonSerializable.toJsonNode(config), - request.apply(config))); - } } diff --git a/src/main/java/com/google/genai/AsyncLive.java b/src/main/java/com/google/genai/AsyncLive.java index 09df8c1babb..0c1b577d297 100644 --- a/src/main/java/com/google/genai/AsyncLive.java +++ b/src/main/java/com/google/genai/AsyncLive.java @@ -36,8 +36,11 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; +import java.util.logging.Level; +import java.util.logging.Logger; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; +import org.jspecify.annotations.Nullable; /** * AsyncLive provides asynchronous access to a bidirectional GenAI live session. The live module is @@ -46,6 +49,7 @@ public class AsyncLive { private final ApiClient apiClient; + private static final Logger logger = Logger.getLogger(AsyncLive.class.getName()); AsyncLive(ApiClient apiClient) { this.apiClient = apiClient; @@ -60,6 +64,12 @@ public class AsyncLive { * connection. */ public CompletableFuture connect(String model, LiveConnectConfig config) { + // TODO: b/404946806 - Support per request HTTP options. + if (config != null && config.httpOptions().isPresent()) { + throw new IllegalArgumentException( + "The AsyncLive module does not support httpOptions at request-level in LiveConnectConfig" + + " yet. Please use the client-level httpOptions configuration instead."); + } CompletableFuture future = new CompletableFuture<>(); GenAiWebSocketClient websocket = @@ -77,7 +87,7 @@ public CompletableFuture connect(String model, LiveConnectConfig c /** Gets the URI for the websocket connection. */ private URI getWebSocketUri() { - String baseUrl = apiClient.httpOptions.baseUrl().orElse(null); + String baseUrl = apiClient.httpOptions().baseUrl().orElse(null); if (baseUrl == null) { throw new IllegalArgumentException("No base URL provided in the client."); } @@ -92,18 +102,38 @@ private URI getWebSocketUri() { baseUri.getFragment()) .toString(); + boolean hasStandardAuth = + (apiClient.project() != null && apiClient.location() != null) + || apiClient.apiKey() != null; + if (apiClient.customBaseUrl() != null && !hasStandardAuth) { + return new URI(wsBaseUrl); + } + if (!apiClient.vertexAI()) { + String method; + if (apiClient.apiKey() != null && apiClient.apiKey().startsWith("auth_tokens/")) { + logger.warning( + "Warning: Ephemeral token support is experimental and may change in future" + + " versions."); + if (!apiClient.httpOptions().apiVersion().orElse("v1beta").equals("v1alpha")) { + logger.warning( + "Warning: The SDK's ephemeral token support is in v1alpha only. Please use client" + + " = Client.builder().httpOptions(HttpOptions.builder().apiVersion(\"v1alpha\").build()).build()" + + " before session connection."); + } + method = "BidiGenerateContentConstrained"; + } else { + method = "BidiGenerateContent"; + } return new URI( String.format( - "%s/ws/google.ai.generativelanguage.%s.GenerativeService.BidiGenerateContent?key=%s", - wsBaseUrl, - apiClient.httpOptions.apiVersion().orElse("v1beta"), - apiClient.apiKey())); + "%s/ws/google.ai.generativelanguage.%s.GenerativeService.%s", + wsBaseUrl, apiClient.httpOptions().apiVersion().orElse("v1beta"), method)); } else { return new URI( String.format( "%s/ws/google.cloud.aiplatform.%s.LlmBidiService/BidiGenerateContent", - wsBaseUrl, apiClient.httpOptions.apiVersion().orElse("v1beta1"))); + wsBaseUrl, apiClient.httpOptions().apiVersion().orElse("v1beta1"))); } } catch (URISyntaxException e) { throw new IllegalStateException("Failed to parse URL.", e); @@ -113,16 +143,31 @@ private URI getWebSocketUri() { /** Gets the headers for the websocket connection. */ private Map getWebSocketHeaders() { Map headers = new HashMap<>(); - apiClient.httpOptions.headers().ifPresent(headers::putAll); + apiClient.httpOptions().headers().ifPresent(headers::putAll); if (apiClient.vertexAI()) { - try { - GoogleCredentials credentials = - apiClient.credentials.orElse(apiClient.defaultCredentials()); - credentials.refreshIfExpired(); - headers.put("Authorization", "Bearer " + credentials.getAccessToken().getTokenValue()); - } catch (IOException e) { - throw new GenAiIOException("Failed to refresh credentials for Vertex AI.", e); + if (apiClient.credentials() != null) { + try { + GoogleCredentials credentials = apiClient.credentials(); + credentials.refreshIfExpired(); + headers.put("Authorization", "Bearer " + credentials.getAccessToken().getTokenValue()); + if (credentials.getQuotaProjectId() != null) { + headers.put("x-goog-user-project", credentials.getQuotaProjectId()); + } + } catch (IOException e) { + throw new GenAiIOException("Failed to refresh credentials for Vertex AI.", e); + } + } else if (apiClient.apiKey() != null) { + headers.put("x-goog-api-key", apiClient.apiKey()); + } + } else { + @Nullable String apiKey = apiClient.apiKey(); + if (apiKey == null) { + throw new IllegalArgumentException("Missing API key in the client."); + } else if (apiKey.startsWith("auth_tokens/")) { + headers.put("Authorization", "Token " + apiKey); + } else { + headers.put("x-goog-api-key", apiKey); } } return headers; @@ -133,7 +178,10 @@ private String getSetupRequest(String model, LiveConnectConfig config) { String transformedModel = Transformers.tModel(apiClient, model); // Vertex requires the full resource path for the model. - if (apiClient.vertexAI() && transformedModel.startsWith("publishers/")) { + if (apiClient.vertexAI() + && transformedModel.startsWith("publishers/") + && apiClient.project() != null + && apiClient.location() != null) { model = String.format( "projects/%s/locations/%s/%s", @@ -210,8 +258,7 @@ public void onMessage(ByteBuffer message) { @Override public void onError(Exception ex) { - System.err.println("Error during live session: " + ex.getMessage()); - ex.printStackTrace(); + logger.log(Level.SEVERE, "Error during live session", ex); if (!sessionFuture.isDone()) { sessionFuture.completeExceptionally(ex); } @@ -219,7 +266,10 @@ public void onError(Exception ex) { @Override public void onClose(int code, String reason, boolean remote) { - System.out.println("Live session closed with code: " + code + " and reason: " + reason); + logger.log( + Level.INFO, + "Live session closed with code: {0} and reason: {1}", + new Object[] {code, reason}); if (!sessionFuture.isDone()) { sessionFuture.completeExceptionally( new GenAiIOException("WebSocket closed unexpectedly: " + reason)); @@ -230,23 +280,44 @@ 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) { + logger.log(Level.SEVERE, "Error deserializing message", e); + 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()); - e.printStackTrace(); + logger.log(Level.SEVERE, "Error deserializing message", e); } } else { - System.err.println( - "Received message from live session but no callback registered! Please call" - + " `AsyncSession.receive()` to register a callback."); + logger.severe( + "Received message from live session, but no callback registered! Please call" + + " `AsyncSession.receive()` to register a callback first."); } } } -} \ No newline at end of file +} diff --git a/src/main/java/com/google/genai/AsyncModels.java b/src/main/java/com/google/genai/AsyncModels.java index 05bd6c277dd..f28cbc5444e 100644 --- a/src/main/java/com/google/genai/AsyncModels.java +++ b/src/main/java/com/google/genai/AsyncModels.java @@ -20,51 +20,379 @@ 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.ComputeTokensParameters; import com.google.genai.types.ComputeTokensResponse; import com.google.genai.types.Content; import com.google.genai.types.CountTokensConfig; +import com.google.genai.types.CountTokensParameters; import com.google.genai.types.CountTokensResponse; import com.google.genai.types.DeleteModelConfig; +import com.google.genai.types.DeleteModelParameters; import com.google.genai.types.DeleteModelResponse; import com.google.genai.types.EditImageConfig; +import com.google.genai.types.EditImageParameters; import com.google.genai.types.EditImageResponse; import com.google.genai.types.EmbedContentConfig; +import com.google.genai.types.EmbedContentParametersPrivate; import com.google.genai.types.EmbedContentResponse; +import com.google.genai.types.EmbeddingApiType; import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.GenerateContentParameters; import com.google.genai.types.GenerateContentResponse; import com.google.genai.types.GenerateImagesConfig; +import com.google.genai.types.GenerateImagesParameters; import com.google.genai.types.GenerateImagesResponse; 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.GetModelConfig; +import com.google.genai.types.GetModelParameters; import com.google.genai.types.Image; import com.google.genai.types.ListModelsConfig; +import com.google.genai.types.ListModelsParameters; +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.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; +import com.google.genai.types.UpscaleImageAPIParameters; 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) { + GenerateContentParameters.Builder parameterBuilder = GenerateContentParameters.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()); + 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, parameterNode); + } + }); + } + + CompletableFuture> privateGenerateContentStream( + String model, List contents, GenerateContentConfig config) { + GenerateContentParameters.Builder parameterBuilder = GenerateContentParameters.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()); + 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, parameterNode); + }); + } + + CompletableFuture privateEmbedContent( + String model, + List contents, + Content content, + EmbeddingApiType embeddingApiType, + EmbedContentConfig config) { + EmbedContentParametersPrivate.Builder parameterBuilder = + EmbedContentParametersPrivate.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(contents)) { + parameterBuilder.contents(contents); + } + if (!Common.isZero(content)) { + parameterBuilder.content(content); + } + if (!Common.isZero(embeddingApiType)) { + parameterBuilder.embeddingApiType(embeddingApiType); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = + models.buildRequestForPrivateEmbedContent( + model, contents, content, embeddingApiType, config); + return this.apiClient + .asyncRequest("post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return models.processResponseForPrivateEmbedContent(res, config, parameterNode); + } + }); + } + + /** Asynchronously private method for generating images. */ + CompletableFuture privateGenerateImages( + 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()); + 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, parameterNode); + } + }); + } + + /** Asynchronously private method for editing an image. */ + CompletableFuture privateEditImage( + String model, + String prompt, + List referenceImages, + EditImageConfig config) { + EditImageParameters.Builder parameterBuilder = EditImageParameters.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(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); + } + + /** Asynchronously private method for upscaling an image. */ + CompletableFuture privateUpscaleImage( + String model, Image image, String upscaleFactor, UpscaleImageAPIConfig config) { + UpscaleImageAPIParameters.Builder parameterBuilder = UpscaleImageAPIParameters.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(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); + } + + /** + * Asynchronously recontextualizes an image. + * + *

    There is one type of recontextualization currently supported: 1) 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 behind an + * allowlist. personImage is required. productImages is required. Only one product image is + * supported currently. + * @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) { + RecontextImageParameters.Builder parameterBuilder = RecontextImageParameters.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(source)) { + parameterBuilder.source(source); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); + } + + /** + * 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) { + SegmentImageParameters.Builder parameterBuilder = SegmentImageParameters.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(source)) { + parameterBuilder.source(source); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); + } + /** * 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)); + GetModelParameters.Builder parameterBuilder = GetModelParameters.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); + } + + CompletableFuture privateList(ListModelsConfig config) { + ListModelsParameters.Builder parameterBuilder = ListModelsParameters.builder(); + + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); } /** @@ -79,7 +407,24 @@ public CompletableFuture get(String model, GetModelConfig config) { * description") .build()); ``` */ public CompletableFuture update(String model, UpdateModelConfig config) { - return CompletableFuture.supplyAsync(() -> models.update(model, config)); + UpdateModelParameters.Builder parameterBuilder = UpdateModelParameters.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); } /** @@ -88,7 +433,25 @@ 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)); + DeleteModelParameters.Builder parameterBuilder = DeleteModelParameters.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); } /** @@ -103,7 +466,27 @@ public CompletableFuture delete(String model, DeleteModelCo */ public CompletableFuture countTokens( String model, List contents, CountTokensConfig config) { - return CompletableFuture.supplyAsync(() -> models.countTokens(model, contents, config)); + CountTokensParameters.Builder parameterBuilder = CountTokensParameters.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()); + 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, parameterNode); + } + }); } /** @@ -118,27 +501,72 @@ public CompletableFuture countTokens( */ public CompletableFuture computeTokens( String model, List contents, ComputeTokensConfig config) { - return CompletableFuture.supplyAsync(() -> models.computeTokens(model, contents, config)); + ComputeTokensParameters.Builder parameterBuilder = ComputeTokensParameters.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()); + 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, parameterNode); + } + }); } - /** - * Asynchronously generates videos given a GenAI model, and a prompt or an image. - * - *

    This method is experimental. - * - * @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 use cases. - * @param image the input image for generating the videos. Optional if prompt is provided. - * @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, String prompt, Image image, GenerateVideosConfig config) { - return CompletableFuture.supplyAsync(() -> models.generateVideos(model, prompt, image, config)); + /** Asynchronously private method for generating videos. */ + CompletableFuture privateGenerateVideos( + String model, + String prompt, + Image image, + Video video, + GenerateVideosSource source, + GenerateVideosConfig config) { + GenerateVideosParameters.Builder parameterBuilder = GenerateVideosParameters.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(video)) { + parameterBuilder.video(video); + } + if (!Common.isZero(source)) { + parameterBuilder.source(source); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); } + private static final Logger logger = Logger.getLogger(AsyncModels.class.getName()); + /** * Asynchronously counts tokens given a GenAI model and a text string. * @@ -151,7 +579,7 @@ public CompletableFuture generateVideos( */ public CompletableFuture countTokens( String model, String text, CountTokensConfig config) { - return CompletableFuture.supplyAsync(() -> models.countTokens(model, text, config)); + return countTokens(model, Transformers.tContents(text), config); } /** @@ -166,7 +594,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); + }); } /** @@ -181,7 +682,57 @@ public CompletableFuture computeTokens( */ public CompletableFuture generateContent( String model, List contents, GenerateContentConfig config) { - return CompletableFuture.supplyAsync(() -> models.generateContent(model, contents, config)); + ImmutableList incompatibleToolsIndexes = + AfcUtil.findAfcIncompatibleToolIndexes(config); + GenerateContentConfig transformedConfig = AfcUtil.transformGenerateContentConfig(config); + if (AfcUtil.shouldDisableAfc(transformedConfig)) { + return privateGenerateContent(model, contents, transformedConfig); + } + if (!incompatibleToolsIndexes.isEmpty()) { + int originalToolsSize = 0; + if (config.tools().isPresent() && !config.tools().get().isEmpty()) { + originalToolsSize = config.tools().get().size(); + } + if (originalToolsSize != incompatibleToolsIndexes.size()) { + logger.warning( + String.format( + "Automatic function calling is enabled, but the following tools are not supported:" + + " %s. AFC will be disabled.", + incompatibleToolsIndexes)); + } + 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; + }); } /** @@ -227,8 +778,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); } /** @@ -274,7 +833,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); } /** @@ -296,9 +856,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); } /** @@ -314,8 +877,66 @@ 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); + } + + /** + * Asynchronously generates videos given a GenAI model, and an input (text, image, or video). + * + *

    This method is experimental. + * + * @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 + * optional configurations + * @return a {@link com.google.genai.types.GenerateVideosOperation} instance that contains the + * generated videos. + */ + public CompletableFuture generateVideos( + String model, String prompt, Image image, Video video, GenerateVideosConfig config) { + return privateGenerateVideos(model, prompt, image, models.preProcessVideo(video), null, config); + } + + /** + * Asynchronously generates videos given a GenAI model, and an input (text, image). + * + *

    This method is experimental, and kept for backward compatibility. + * + * @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 use cases. + * @param image the input image for generating the videos. Optional if prompt is provided. + * @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, String prompt, Image image, GenerateVideosConfig config) { + return generateVideos(model, prompt, image, null, config); } /** @@ -328,7 +949,7 @@ public CompletableFuture upscaleImage( */ public CompletableFuture embedContent( String model, String text, EmbedContentConfig config) { - return CompletableFuture.supplyAsync(() -> models.embedContent(model, text, config)); + return embedContent(model, ImmutableList.of(text), config); } /** @@ -341,7 +962,50 @@ 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))); + } + Content content = null; + if (!contents.isEmpty()) { + content = contents.get(0); + } + boolean isVertexEmbedContentModel = + this.apiClient.vertexAI() && Transformers.tIsVertexEmbedContentModel(model); + if (isVertexEmbedContentModel && contents.size() > 1) { + throw new IllegalArgumentException( + "The embedContent API for this model only supports one content at a time."); + } + EmbeddingApiType apiType = + isVertexEmbedContentModel + ? new EmbeddingApiType("EMBED_CONTENT") + : new EmbeddingApiType("PREDICT"); + return privateEmbedContent(model, contents, content, apiType, config); + } + + /** + * Asynchronously embeds content given a GenAI model and a content object. + * + * @param model the name of the GenAI model to use for embedding + * @param content a {@link com.google.genai.types.Content} to send to the embedding model + * @return a {@link com.google.genai.types.EmbedContentResponse} instance that contains the + * embedding. + */ + public CompletableFuture embedContent( + String model, Content content, EmbedContentConfig config) { + List contents = new ArrayList<>(); + contents.add(content); + boolean isVertexEmbedContentModel = + this.apiClient.vertexAI() && Transformers.tIsVertexEmbedContentModel(model); + if (isVertexEmbedContentModel && contents.size() > 1) { + throw new IllegalArgumentException( + "The embedContent API for this model only supports one content at a time."); + } + EmbeddingApiType apiType = + isVertexEmbedContentModel + ? new EmbeddingApiType("EMBED_CONTENT") + : new EmbeddingApiType("PREDICT"); + return privateEmbedContent(model, contents, content, apiType, config); } /** @@ -375,10 +1039,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..5a6057332db 100644 --- a/src/main/java/com/google/genai/AsyncOperations.java +++ b/src/main/java/com/google/genai/AsyncOperations.java @@ -18,18 +18,56 @@ 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 +77,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..a87b8f6a2dd 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; @@ -99,8 +101,7 @@ public CompletableFuture forEach(Consumer itemAction) { failedFuture.completeExceptionally(new IllegalArgumentException("Action cannot be null.")); return failedFuture; } - return initializationFuture - .thenCompose(v -> processPageItemsAndContinue(page, itemAction)); + return initializationFuture.thenCompose(v -> processPageItemsAndContinue(page, itemAction)); } private CompletableFuture processPageItemsAndContinue( @@ -149,4 +150,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 d5214c201b1..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; } /** @@ -100,9 +102,9 @@ private CompletableFuture send(LiveClientMessage input) { ObjectNode body; if (this.apiClient.vertexAI()) { - body = liveConverters.liveClientMessageToVertex(this.apiClient, parameterNode, null); + body = liveConverters.liveClientMessageToVertex(parameterNode, null); } else { - body = liveConverters.liveClientMessageToMldev(this.apiClient, parameterNode, null); + body = liveConverters.liveClientMessageToMldev(parameterNode, null); } return CompletableFuture.runAsync(() -> websocket.send(JsonSerializable.toJsonString(body))); @@ -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/AsyncTokens.java b/src/main/java/com/google/genai/AsyncTokens.java new file mode 100644 index 00000000000..3867a96e457 --- /dev/null +++ b/src/main/java/com/google/genai/AsyncTokens.java @@ -0,0 +1,52 @@ +/* + * 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.Common.BuiltRequest; +import com.google.genai.types.AuthToken; +import com.google.genai.types.CreateAuthTokenConfig; +import java.util.concurrent.CompletableFuture; + +/** Async module of {@link AuthToken} */ +public final class AsyncTokens { + + Tokens tokens; + ApiClient apiClient; + + public AsyncTokens(ApiClient apiClient) { + this.apiClient = apiClient; + this.tokens = new Tokens(apiClient); + } + + /** + * Asynchronously creates an ephemeral auth token resource. + * + * @param config A {@link CreateAuthTokenConfig} for configuring the create request. + * @return A {@link AuthToken} object that contains the info of the created resource. + */ + public CompletableFuture create(CreateAuthTokenConfig config) { + BuiltRequest builtRequest = tokens.buildRequestForCreate(config); + return this.apiClient + .asyncRequest("post", builtRequest.path, builtRequest.body, builtRequest.httpOptions) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return tokens.processResponseForCreate(res, config); + } + }); + } +} diff --git a/src/main/java/com/google/genai/AsyncTunings.java b/src/main/java/com/google/genai/AsyncTunings.java new file mode 100644 index 00000000000..8343fb39e9e --- /dev/null +++ b/src/main/java/com/google/genai/AsyncTunings.java @@ -0,0 +1,281 @@ +/* + * 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.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.CancelTuningJobResponse; +import com.google.genai.types.CreateTuningJobConfig; +import com.google.genai.types.CreateTuningJobParametersPrivate; +import com.google.genai.types.GetTuningJobConfig; +import com.google.genai.types.GetTuningJobParameters; +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.util.concurrent.CompletableFuture; +import java.util.function.Function; + +/** 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) { + GetTuningJobParameters.Builder parameterBuilder = GetTuningJobParameters.builder(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); + } + + CompletableFuture privateList(ListTuningJobsConfig config) { + ListTuningJobsParameters.Builder parameterBuilder = ListTuningJobsParameters.builder(); + + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); + } + + /** + * Asynchronously cancels a tuning job resource. + * + * @param name The resource name of the tuning job. For Gemini Enterprise Agent Platform , 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) { + 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()); + BuiltRequest builtRequest = tunings.buildRequestForCancel(name, config); + return this.apiClient + .asyncRequest("post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()) + .thenApplyAsync( + response -> { + try (ApiResponse res = response) { + return tunings.processResponseForCancel(res, config, parameterNode); + } + }); + } + + CompletableFuture privateTune( + String baseModel, + PreTunedModel preTunedModel, + TuningDataset trainingDataset, + CreateTuningJobConfig config) { + 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); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); + } + + CompletableFuture privateTuneMldev( + String baseModel, + PreTunedModel preTunedModel, + TuningDataset trainingDataset, + CreateTuningJobConfig config) { + 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); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + 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, parameterNode); + } + }); + } + + /** + * Asynchronously makes an API request to list the available tuning jobs. + * + * @param config A {@link ListTuningJobsConfig} for configuring the list request. + * @return A CompletableFuture that resolves to a {@link AsyncPager}. The AsyncPager has a + * `forEach` method that can be used to asynchronously process items in the page and + * automatically query the next page once the current page is exhausted. + */ + @SuppressWarnings("PatternMatchingInstanceof") + public CompletableFuture> list(ListTuningJobsConfig config) { + if (config == null) { + config = ListTuningJobsConfig.builder().build(); + } + ListTuningJobsConfig finalConfig = config; + Function> request = + requestConfig -> { + if (!(requestConfig instanceof ListTuningJobsConfig)) { + throw new GenAiIOException( + "Internal error: Pager expected ListTuningJobsConfig but received " + + requestConfig.getClass().getName()); + } + return this.privateList((ListTuningJobsConfig) requestConfig) + .thenApply(JsonSerializable::toJsonNode); + }; + return CompletableFuture.supplyAsync( + () -> + new AsyncPager( + Pager.PagedItem.TUNING_JOBS, + request, + (ObjectNode) JsonSerializable.toJsonNode(finalConfig), + request.apply(finalConfig))); + } + + /** + * Asynchronously makes an API request to get a tuning job. + * + * @param name The resource name of the tuning job. + * @param config A {@link GetTuningJobConfig} for configuring the get request. + * @return A CompletableFuture that resolves to a {@link TuningJob} object. + */ + public CompletableFuture get(String name, GetTuningJobConfig config) { + return CompletableFuture.supplyAsync(() -> tunings.privateGet(name, config)); + } + + /** + * Asynchronously makes an API request to create a supervised fine-tuning job. + * + *

    This method is experimental. + * + * @param baseModel The base model to tune. + * @param trainingDataset The training dataset to use for tuning. + * @param config A {@link CreateTuningJobConfig} for configuring the create request. + * @return A CompletableFuture that resolves to a {@link TuningJob} object. + */ + public CompletableFuture tune( + String baseModel, TuningDataset trainingDataset, CreateTuningJobConfig config) { + + if (tunings.apiClient.vertexAI()) { + CompletableFuture tuningJobFuture; + if (baseModel.startsWith("projects/")) { + PreTunedModel.Builder preTunedModelBuilder = + PreTunedModel.builder().tunedModelName(baseModel); + if (config != null && config.preTunedModelCheckpointId().isPresent()) { + preTunedModelBuilder.checkpointId(config.preTunedModelCheckpointId().get()); + } + tuningJobFuture = + this.privateTune(null, preTunedModelBuilder.build(), trainingDataset, config); + } else { + tuningJobFuture = this.privateTune(baseModel, null, trainingDataset, config); + } + if (config != null && config.evaluationConfig().isPresent()) { + return tuningJobFuture.thenApply( + tuningJob -> + tuningJob.toBuilder().evaluationConfig(config.evaluationConfig().get()).build()); + } + return tuningJobFuture; + } 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 e342d0e5b34..cdae046ec63 100644 --- a/src/main/java/com/google/genai/BasePager.java +++ b/src/main/java/com/google/genai/BasePager.java @@ -20,12 +20,21 @@ 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.Document; import com.google.genai.types.File; +import com.google.genai.types.FileSearchStore; +import com.google.genai.types.HttpResponse; +import com.google.genai.types.ListBatchJobsConfig; import com.google.genai.types.ListCachedContentsConfig; +import com.google.genai.types.ListDocumentsConfig; +import com.google.genai.types.ListFileSearchStoresConfig; import com.google.genai.types.ListFilesConfig; import com.google.genai.types.ListModelsConfig; +import com.google.genai.types.ListTuningJobsConfig; import com.google.genai.types.Model; +import com.google.genai.types.TuningJob; import java.util.ArrayList; import java.util.List; @@ -36,7 +45,11 @@ abstract class BasePager { static enum PagedItem { MODELS("models", Model.class, ListModelsConfig.class), CACHED_CONTENTS("cachedContents", CachedContent.class, ListCachedContentsConfig.class), - FILES("files", File.class, ListFilesConfig.class); + FILES("files", File.class, ListFilesConfig.class), + BATCH_JOBS("batchJobs", BatchJob.class, ListBatchJobsConfig.class), + TUNING_JOBS("tuningJobs", TuningJob.class, ListTuningJobsConfig.class), + DOCUMENTS("documents", Document.class, ListDocumentsConfig.class), + FILE_SEARCH_STORES("fileSearchStores", FileSearchStore.class, ListFileSearchStoresConfig.class); private final String fieldName; private final Class itemClass; @@ -73,6 +86,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) { @@ -93,17 +107,22 @@ protected void initNewPage(JsonNode response) { throw new IllegalArgumentException("Response cannot be null."); } JsonNode responseList = response.get(pagedItem.fieldName()); + // Sets the page. if (responseList == null) { - throw new GenAiIOException( - "Response does not contain the requested item. Raw response: " - + JsonSerializable.toJsonString(response)); + this.page = ImmutableList.of(); + } else { + List page = new ArrayList<>(); + for (JsonNode responseItem : responseList) { + page.add((T) JsonSerializable.fromJsonNode(responseItem, pagedItem.itemClass())); + } + this.page = ImmutableList.copyOf(page); } - // Sets the page. - List page = new ArrayList<>(); - for (JsonNode responseItem : responseList) { - page.add((T) JsonSerializable.fromJsonNode(responseItem, pagedItem.itemClass())); + try { + this.sdkHttpResponse = + JsonSerializable.fromJsonNode(response.get("sdkHttpResponse"), HttpResponse.class); + } catch (GenAiIOException e) { + this.sdkHttpResponse = null; } - this.page = ImmutableList.copyOf(page); // 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 new file mode 100644 index 00000000000..8bcff49f15a --- /dev/null +++ b/src/main/java/com/google/genai/Batches.java @@ -0,0 +1,2753 @@ +/* + * 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.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; +import com.google.genai.types.CancelBatchJobConfig; +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; + +/** + * Provides methods for managing the batch jobs. Instantiating this class is not required. After + * instantiating a {@link Client}, access methods through `client.batches.methodName(...)` directly. + */ +public final class Batches { + + final ApiClient apiClient; + + public Batches(ApiClient apiClient) { + this.apiClient = apiClient; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode authConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"apiKey"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"apiKey"}, + Common.getValueByPath(fromObject, new String[] {"apiKey"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}))) { + throw new IllegalArgumentException( + "apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"authType"}))) { + throw new IllegalArgumentException( + "authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"}))) { + throw new IllegalArgumentException( + "googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent" + + " Platform mode, not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}))) { + throw new IllegalArgumentException( + "httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"oauthConfig"}))) { + throw new IllegalArgumentException( + "oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"oidcConfig"}))) { + throw new IllegalArgumentException( + "oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + 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); + } + + if (Common.getValueByPath( + fromObject, new String[] {"inlinedEmbedContentResponses", "inlinedResponses"}) + != null) { + Common.setValueByPath( + toObject, + new String[] {"inlinedEmbedContentResponses"}, + Common.getValueByPath( + fromObject, new String[] {"inlinedEmbedContentResponses", "inlinedResponses"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode batchJobDestinationFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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[] {"gcsDestination", "outputUriPrefix"}) + != null) { + Common.setValueByPath( + toObject, + new String[] {"gcsUri"}, + Common.getValueByPath(fromObject, new String[] {"gcsDestination", "outputUriPrefix"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"bigqueryDestination", "outputUri"}) + != null) { + Common.setValueByPath( + toObject, + new String[] {"bigqueryUri"}, + Common.getValueByPath(fromObject, new String[] {"bigqueryDestination", "outputUri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"vertexMultimodalDatasetDestination"}) + != null) { + Common.setValueByPath( + toObject, + new String[] {"vertexDataset"}, + vertexMultimodalDatasetDestinationFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath( + fromObject, new String[] {"vertexMultimodalDatasetDestination"})), + toObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode batchJobDestinationToVertex(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) { + Common.setValueByPath( + toObject, + new String[] {"gcsDestination", "outputUriPrefix"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"bigqueryUri"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"bigqueryDestination", "outputUri"}, + Common.getValueByPath(fromObject, new String[] {"bigqueryUri"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"fileName"}))) { + throw new IllegalArgumentException( + "fileName parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"inlinedResponses"}))) { + throw new IllegalArgumentException( + "inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"inlinedEmbedContentResponses"}))) { + throw new IllegalArgumentException( + "inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode," + + " not in Gemini Enterprise Agent Platform mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"vertexDataset"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"vertexMultimodalDatasetDestination"}, + vertexMultimodalDatasetDestinationToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"vertexDataset"})), + toObject)); + } + + 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[] {"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) { + Common.setValueByPath( + toObject, + new String[] {"endTime"}, + Common.getValueByPath(fromObject, new String[] {"metadata", "endTime"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"metadata", "updateTime"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"updateTime"}, + Common.getValueByPath(fromObject, new String[] {"metadata", "updateTime"})); + } + + 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[] {"metadata", "output"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"dest"}, + batchJobDestinationFromMldev( + JsonSerializable.toJsonNode( + Transformers.tRecvBatchJobDestination( + Common.getValueByPath(fromObject, new String[] {"metadata", "output"}))), + toObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode batchJobFromVertex(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"}, + Common.getValueByPath(fromObject, new String[] {"error"})); + } + + 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) { + Common.setValueByPath( + toObject, + new String[] {"model"}, + Common.getValueByPath(fromObject, new String[] {"model"})); + } + + 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.getValueByPath(fromObject, new String[] {"outputConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"dest"}, + batchJobDestinationFromVertex( + JsonSerializable.toJsonNode( + Transformers.tRecvBatchJobDestination( + Common.getValueByPath(fromObject, new String[] {"outputConfig"}))), + toObject)); + } + + if (Common.getValueByPath(fromObject, new String[] {"completionStats"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"completionStats"}, + Common.getValueByPath(fromObject, new String[] {"completionStats"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"outputInfo"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"outputInfo"}, + Common.getValueByPath(fromObject, new String[] {"outputInfo"})); + } + + 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) { + Common.setValueByPath( + toObject, + new String[] {"bigqueryUri"}, + Common.getValueByPath(fromObject, new String[] {"bigquerySource", "inputUri"})); + } + + if (Common.getValueByPath( + fromObject, new String[] {"vertexMultimodalDatasetSource", "datasetName"}) + != null) { + Common.setValueByPath( + toObject, + new String[] {"vertexDatasetName"}, + Common.getValueByPath( + fromObject, new String[] {"vertexMultimodalDatasetSource", "datasetName"})); + } + + 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 only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"gcsUri"}))) { + throw new IllegalArgumentException( + "gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"bigqueryUri"}))) { + throw new IllegalArgumentException( + "bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"fileName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"fileName"}, + Common.getValueByPath(fromObject, new String[] {"fileName"})); + } + + 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(); + + for (JsonNode item : keyArray) { + result.add(inlinedRequestToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"requests", "requests"}, result); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"vertexDatasetName"}))) { + throw new IllegalArgumentException( + "vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode batchJobSourceToVertex(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) { + Common.setValueByPath( + toObject, + new String[] {"gcsSource", "uris"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"bigqueryUri"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"bigquerySource", "inputUri"}, + Common.getValueByPath(fromObject, new String[] {"bigqueryUri"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"fileName"}))) { + throw new IllegalArgumentException( + "fileName parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"inlinedRequests"}))) { + throw new IllegalArgumentException( + "inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"vertexDatasetName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"vertexMultimodalDatasetSource", "datasetName"}, + Common.getValueByPath(fromObject, new String[] {"vertexDatasetName"})); + } + + return toObject; + } + + @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[] {"data"}, + Common.getValueByPath(fromObject, new String[] {"data"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException( + "displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode cancelBatchJobParametersToMldev( + 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 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"}))); + } + + 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"}, + Common.getValueByPath(fromObject, new String[] {"content"})); + } + + 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[] {"groundingMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"groundingMetadata"}, + Common.getValueByPath(fromObject, new String[] {"groundingMetadata"})); + } + + 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[] {"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"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"urlContextMetadata"}, + Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"})); + } + + 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 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[] {"role"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"role"}, + Common.getValueByPath(fromObject, new String[] {"role"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode createBatchJobConfigToMldev(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[] {"dest"}))) { + throw new IllegalArgumentException( + "dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"webhookConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"batch", "webhookConfig"}, + Common.getValueByPath(fromObject, new String[] {"webhookConfig"})); + } + + 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)); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"webhookConfig"}))) { + throw new IllegalArgumentException( + "webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode createBatchJobParametersToMldev( + 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[] {"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 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) { + 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 createEmbeddingsBatchJobParametersToMldev( + 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[] {"src"}) != null) { + Common.setValueByPath( + toObject, + 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 deleteBatchJobParametersToMldev( + 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 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 deleteResourceJobFromMldev(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 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[] {"config"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_self"}, + embedContentConfigToMldev( + JsonSerializable.toJsonNode( + 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 only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"autoTruncate"}))) { + throw new IllegalArgumentException( + "autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"documentOcr"}))) { + throw new IllegalArgumentException( + "documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audioTrackExtraction"}))) { + throw new IllegalArgumentException( + "audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + 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[] {"requests"}, + embedContentBatchToMldev( + apiClient, + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"inlinedRequests"})), + toObject)); + } + + 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 only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + 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 functionCallToMldev(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"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"partialArgs"}))) { + throw new IllegalArgumentException( + "partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"willContinue"}))) { + throw new IllegalArgumentException( + "willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode functionCallingConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"allowedFunctionNames"}, + Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mode"}, + Common.getValueByPath(fromObject, new String[] {"mode"})); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"streamFunctionCallArguments"}))) { + throw new IllegalArgumentException( + "streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent" + + " Platform mode, not in Gemini Developer API mode."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generateContentConfigToMldev( + 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"}, + contentToMldev( + 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"}, + Transformers.tSchema(Common.getValueByPath(fromObject, new String[] {"responseSchema"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != 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 only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}))) { + throw new IllegalArgumentException( + "modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + 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[] {"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[] {"toolConfig"}) != 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[] {"labels"}))) { + throw new IllegalArgumentException( + "labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + 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"}, + Transformers.tSpeechConfig( + Common.getValueByPath(fromObject, new String[] {"speechConfig"}))); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audioTimestamp"}))) { + throw new IllegalArgumentException( + "audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + 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"}, + imageConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"imageConfig"})), + toObject)); + } + + if (Common.getValueByPath(fromObject, new String[] {"enableEnhancedCivicAnswers"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"enableEnhancedCivicAnswers"}, + Common.getValueByPath(fromObject, new String[] {"enableEnhancedCivicAnswers"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"modelArmorConfig"}))) { + throw new IllegalArgumentException( + "modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"serviceTier"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"serviceTier"}, + Common.getValueByPath(fromObject, new String[] {"serviceTier"})); + } + + 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[] {"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"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"modelStatus"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"modelStatus"}, + Common.getValueByPath(fromObject, new String[] {"modelStatus"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode getBatchJobParametersToMldev( + 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 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"}))); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode googleMapsToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"authConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"authConfig"}, + authConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"authConfig"})), + toObject)); + } + + if (Common.getValueByPath(fromObject, new String[] {"enableWidget"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"enableWidget"}, + Common.getValueByPath(fromObject, new String[] {"enableWidget"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"searchTypes"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"searchTypes"}, + Common.getValueByPath(fromObject, new String[] {"searchTypes"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"blockingConfidence"}))) { + throw new IllegalArgumentException( + "blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"excludeDomains"}))) { + throw new IllegalArgumentException( + "excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"timeRangeFilter"}, + Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode imageConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"imageSize"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"imageSize"}, + Common.getValueByPath(fromObject, new String[] {"imageSize"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"personGeneration"}))) { + throw new IllegalArgumentException( + "personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"prominentPeople"}))) { + throw new IllegalArgumentException( + "prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"outputMimeType"}))) { + throw new IllegalArgumentException( + "outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}))) { + throw new IllegalArgumentException( + "outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"imageOutputOptions"}))) { + throw new IllegalArgumentException( + "imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + 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[] {"request", "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(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[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"request", "generationConfig"}, + generateContentConfigToMldev( + apiClient, + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + (ObjectNode) + Common.getValueByPath( + toObject, + new String[] {"request"}, + (new ObjectMapper()).createObjectNode()))); + } + + 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[] {"metadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listBatchJobsConfigToMldev(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.isZero(Common.getValueByPath(fromObject, new String[] {"filter"}))) { + throw new IllegalArgumentException( + "filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + 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 listBatchJobsParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + listBatchJobsConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listBatchJobsParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + listBatchJobsConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listBatchJobsResponseFromMldev(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[] {"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 listBatchJobsResponseFromVertex(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[] {"batchPredictionJobs"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"batchPredictionJobs"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(batchJobFromVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"batchJobs"}, result); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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[] {"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[] {"fileData"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"fileData"}, + fileDataToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"fileData"})), + toObject)); + } + + if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"functionCall"}, + functionCallToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"functionCall"})), + toObject)); + } + + 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[] {"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, + new String[] {"text"}, + 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"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"toolCall"}, + Common.getValueByPath(fromObject, new String[] {"toolCall"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"toolResponse"}, + Common.getValueByPath(fromObject, new String[] {"toolResponse"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"partMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"partMetadata"}, + Common.getValueByPath(fromObject, new String[] {"partMetadata"})); + } + + 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[] {"category"}, + Common.getValueByPath(fromObject, new String[] {"category"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"method"}))) { + throw new IllegalArgumentException( + "method parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"threshold"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"threshold"}, + Common.getValueByPath(fromObject, new String[] {"threshold"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode toolConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"retrievalConfig"}, + Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})); + } + + 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.getValueByPath(fromObject, new String[] {"includeServerSideToolInvocations"}) + != null) { + Common.setValueByPath( + toObject, + new String[] {"includeServerSideToolInvocations"}, + Common.getValueByPath(fromObject, new String[] {"includeServerSideToolInvocations"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { + throw new IllegalArgumentException( + "retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"fileSearch"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"fileSearch"}, + Common.getValueByPath(fromObject, new String[] {"fileSearch"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"googleSearch"}, + googleSearchToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"googleSearch"})), + 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)); + } + + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { + throw new IllegalArgumentException( + "enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"parallelAiSearch"}))) { + throw new IllegalArgumentException( + "parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"mcpServers"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mcpServers"}, + Common.getValueByPath(fromObject, new String[] {"mcpServers"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode vertexMultimodalDatasetDestinationFromVertex( + JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"bigqueryDestination", "outputUri"}) + != null) { + Common.setValueByPath( + toObject, + new String[] {"bigqueryDestination"}, + Common.getValueByPath(fromObject, new String[] {"bigqueryDestination", "outputUri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode vertexMultimodalDatasetDestinationToVertex( + JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"bigqueryDestination"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"bigqueryDestination", "outputUri"}, + Common.getValueByPath(fromObject, new String[] {"bigqueryDestination"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); + } + + return toObject; + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateCreate( + String model, BatchJobSource src, CreateBatchJobConfig config) { + + CreateBatchJobParameters.Builder parameterBuilder = CreateBatchJobParameters.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()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = createBatchJobParametersToVertex(this.apiClient, parameterNode, null); + path = Common.formatMap("batchPredictionJobs", body.get("_url")); + } else { + body = createBatchJobParametersToMldev(this.apiClient, parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{model}:batchGenerateContent", body.get("_url")); + } else { + path = "{model}:batchGenerateContent"; + } + } + 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. */ + 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", 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()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = createEmbeddingsBatchJobParametersToMldev(this.apiClient, parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{model}:asyncBatchEmbedContent", body.get("_url")); + } else { + path = "{model}:asyncBatchEmbedContent"; + } + } + 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. */ + 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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + 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(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = getBatchJobParametersToVertex(this.apiClient, parameterNode, null); + path = Common.formatMap("batchPredictionJobs/{name}", body.get("_url")); + } else { + body = getBatchJobParametersToMldev(this.apiClient, parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("batches/{name}", body.get("_url")); + } else { + path = "batches/{name}"; + } + } + 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. */ + 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); + } + + /** + * 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 Gemini Enterprise Agent Platform 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) { + 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(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = cancelBatchJobParametersToVertex(this.apiClient, parameterNode, null); + path = Common.formatMap("batchPredictionJobs/{name}:cancel", body.get("_url")); + } else { + body = cancelBatchJobParametersToMldev(this.apiClient, parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("batches/{name}:cancel", body.get("_url")); + } else { + path = "batches/{name}:cancel"; + } + } + 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 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(); + + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = listBatchJobsParametersToVertex(parameterNode, null); + path = Common.formatMap("batchPredictionJobs", body.get("_url")); + } else { + body = listBatchJobsParametersToMldev(parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("batches", body.get("_url")); + } else { + path = "batches"; + } + } + 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. */ + 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", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateList(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForDelete(String name, DeleteBatchJobConfig config) { + + DeleteBatchJobParameters.Builder parameterBuilder = DeleteBatchJobParameters.builder(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = deleteBatchJobParametersToVertex(this.apiClient, parameterNode, null); + path = Common.formatMap("batchPredictionJobs/{name}", body.get("_url")); + } else { + body = deleteBatchJobParametersToMldev(this.apiClient, parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("batches/{name}", body.get("_url")); + } else { + path = "batches/{name}"; + } + } + 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. */ + 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 Gemini Enterprise Agent Platform 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", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForDelete(response, config); + } + } + + /** + * Makes an API request to list the available batch jobs. + * + * @param config A {@link ListBatchJobsConfig} for configuring the list request. + * @return A {@link Pager} object that contains the list of batch jobs. The pager is an iterable + * and automatically queries the next page once the current page is exhausted. + */ + @SuppressWarnings("PatternMatchingInstanceof") + public Pager list(ListBatchJobsConfig config) { + if (config == null) { + config = ListBatchJobsConfig.builder().build(); + } + Function request = + requestConfig -> { + if (!(requestConfig instanceof ListBatchJobsConfig)) { + throw new GenAiIOException( + "Internal error: Pager expected ListBatchJobsConfig but received " + + requestConfig.getClass().getName()); + } + return this.privateList((ListBatchJobsConfig) requestConfig); + }; + return new Pager<>( + Pager.PagedItem.BATCH_JOBS, + request, + (ObjectNode) JsonSerializable.toJsonNode(config), + JsonSerializable.toJsonNode(privateList(config))); + } + + /** + * Makes an API request to create the batch job. + * + * @param model the name of the GenAI model to use for generation + * @param src The {@link BatchJobSource} of the batch job. + * @param config The configuration {@link CreateBatchJobConfig} for the batch job. + * @return A BatchJob. + */ + public BatchJob create(String model, BatchJobSource src, CreateBatchJobConfig config) { + if (this.apiClient.vertexAI()) { + if (src.inlinedRequests().isPresent()) { + throw new GenAiIOException( + "inlinedRequests is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } + if (src.fileName().isPresent()) { + throw new GenAiIOException( + "fileName is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + int count = 0; + if (src.gcsUri().isPresent()) { + count++; + } + if (src.bigqueryUri().isPresent()) { + count++; + } + if (src.vertexDatasetName().isPresent()) { + count++; + } + if (count > 1) { + throw new GenAiIOException( + "Only one of gcsUri, bigqueryUri, and vertexDatasetName can be set."); + } + if (count == 0) { + throw new GenAiIOException("One of gcsUri, bigqueryUri, or vertexDatasetName 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 BatchJob createEmbeddings( + String model, EmbeddingsBatchJobSource src, CreateEmbeddingsBatchJobConfig config) { + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support" + + " batches.createEmbeddings."); + } + return this.privateCreateEmbeddings(model, src, config); + } +} diff --git a/src/main/java/com/google/genai/Caches.java b/src/main/java/com/google/genai/Caches.java index fc0bca692ec..e760b8cb688 100644 --- a/src/main/java/com/google/genai/Caches.java +++ b/src/main/java/com/google/genai/Caches.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.CachedContent; import com.google.genai.types.CreateCachedContentConfig; @@ -32,20 +33,26 @@ 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 org.apache.http.HttpEntity; -import org.apache.http.util.EntityUtils; +import okhttp3.Headers; +import okhttp3.ResponseBody; /** * Provides methods for managing the cached content. Instantiating this class is not required. After * instantiating a {@link Client}, access methods through `client.caches.methodName(...)` directly. */ public final class Caches { + final ApiClient apiClient; public Caches(ApiClient apiClient) { @@ -53,177 +60,91 @@ public Caches(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToMldev( - ApiClient apiClient, 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) { + ObjectNode authConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"apiKey"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"apiKey"}, + Common.getValueByPath(fromObject, new String[] {"apiKey"})); } - 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(ApiClient apiClient, 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.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}))) { + throw new IllegalArgumentException( + "apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } - 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[] {"authType"}))) { + throw new IllegalArgumentException( + "authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - 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[] {"googleServiceAccountConfig"}))) { + throw new IllegalArgumentException( + "googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent" + + " Platform mode, not in Gemini Developer API mode."); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToMldev(ApiClient apiClient, 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.isZero(Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}))) { + throw new IllegalArgumentException( + "httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"oauthConfig"}))) { + throw new IllegalArgumentException( + "oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - 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[] {"oidcConfig"}))) { + throw new IllegalArgumentException( + "oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode partToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataToMldev( - apiClient, - 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( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataToMldev( - apiClient, - 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) { + ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + new String[] {"data"}, + Common.getValueByPath(fromObject, new String[] {"data"})); } - 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[] {"displayName"}))) { + throw new IllegalArgumentException( + "displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(partToMldev(JsonSerializable.toJsonNode(item), toObject)); } Common.setValueByPath(toObject, new String[] {"parts"}, result); } @@ -239,375 +160,111 @@ ObjectNode contentToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode p } @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"behavior"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"behavior"}, - Common.getValueByPath(fromObject, new String[] {"behavior"})); - } - - 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[] {"response"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToMldev(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) { - Common.setValueByPath( - toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"timeRangeFilter"}, - intervalToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToMldev( - 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"})); - } + 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(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); + for (JsonNode item : keyArray) { + result.add(partToVertex(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"parts"}, result); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode enterpriseWebSearchToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode apiKeyConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyString"}))) { - throw new IllegalArgumentException("apiKeyString parameter is not supported in Gemini API."); + new String[] {"role"}, + Common.getValueByPath(fromObject, new String[] {"role"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode authConfigToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}))) { - throw new IllegalArgumentException("apiKeyConfig parameter is not supported in Gemini API."); - } - - 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"})); - } + ObjectNode createCachedContentConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { Common.setValueByPath( - toObject, - new String[] {"httpBasicAuthConfig"}, - Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"})); + parentObject, + new String[] {"ttl"}, + Common.getValueByPath(fromObject, new String[] {"ttl"})); } - if (Common.getValueByPath(fromObject, new String[] {"oauthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { Common.setValueByPath( - toObject, - new String[] {"oauthConfig"}, - Common.getValueByPath(fromObject, new String[] {"oauthConfig"})); + parentObject, + new String[] {"expireTime"}, + Common.getValueByPath(fromObject, new String[] {"expireTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"oidcConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { Common.setValueByPath( - toObject, - new String[] {"oidcConfig"}, - Common.getValueByPath(fromObject, new String[] {"oidcConfig"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleMapsToMldev(ApiClient apiClient, 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."); + parentObject, + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); + (ArrayNode) + Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add( - functionDeclarationToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(contentToMldev(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) { - Common.setValueByPath( - toObject, - new String[] {"googleSearch"}, - googleSearchToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - 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."); + Common.setValueByPath(parentObject, new String[] {"contents"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( - toObject, - new String[] {"urlContext"}, - urlContextToMldev( - apiClient, + parentObject, + new String[] {"systemInstruction"}, + contentToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionCallingConfigToMldev( - 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[] {"allowedFunctionNames"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"allowedFunctionNames"}, - Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode latLngToMldev(ApiClient apiClient, 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 retrievalConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latLng"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"latLng"}, - latLngToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"latLng"})), - 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(); - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + for (JsonNode item : keyArray) { + result.add(toolToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(parentObject, new String[] {"tools"}, result); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolConfigToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionCallingConfig"}, - functionCallingConfigToMldev( - apiClient, + parentObject, + new String[] {"toolConfig"}, + toolConfigToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})), + Common.getValueByPath(fromObject, new String[] {"toolConfig"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"retrievalConfig"}, - retrievalConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"kmsKeyName"}))) { + throw new IllegalArgumentException( + "kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createCachedContentConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode createCachedContentConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { Common.setValueByPath( @@ -633,13 +290,12 @@ ObjectNode createCachedContentConfigToMldev( if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { ArrayNode keyArray = (ArrayNode) - Transformers.tContents( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"})); + Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(contentToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(contentToVertex(JsonSerializable.toJsonNode(item), toObject)); } Common.setValueByPath(parentObject, new String[] {"contents"}, result); } @@ -648,11 +304,9 @@ ObjectNode createCachedContentConfigToMldev( Common.setValueByPath( parentObject, new String[] {"systemInstruction"}, - contentToMldev( - apiClient, + contentToVertex( JsonSerializable.toJsonNode( Transformers.tContent( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), toObject)); } @@ -663,7 +317,7 @@ ObjectNode createCachedContentConfigToMldev( ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(toolToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(toolToVertex(JsonSerializable.toJsonNode(item), toObject)); } Common.setValueByPath(parentObject, new String[] {"tools"}, result); } @@ -672,15 +326,17 @@ ObjectNode createCachedContentConfigToMldev( Common.setValueByPath( parentObject, new String[] {"toolConfig"}, - toolConfigToMldev( - apiClient, + toolConfigToVertex( 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."); + if (Common.getValueByPath(fromObject, new String[] {"kmsKeyName"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"encryption_spec", "kmsKeyName"}, + Common.getValueByPath(fromObject, new String[] {"kmsKeyName"})); } return toObject; @@ -689,7 +345,7 @@ ObjectNode createCachedContentConfigToMldev( @ExcludeFromGeneratedCoverageReport ObjectNode createCachedContentParametersToMldev( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, @@ -699,36 +355,34 @@ ObjectNode createCachedContentParametersToMldev( } if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, + JsonNode unused = createCachedContentConfigToMldev( - apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode getCachedContentParametersToMldev( + ObjectNode createCachedContentParametersToVertex( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tCachedContentName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); + 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"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + JsonNode unused = + createCachedContentConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; @@ -737,7 +391,7 @@ ObjectNode getCachedContentParametersToMldev( @ExcludeFromGeneratedCoverageReport ObjectNode deleteCachedContentParametersToMldev( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, @@ -746,1027 +400,892 @@ ObjectNode deleteCachedContentParametersToMldev( 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 listCachedContentsConfigToMldev( + ObjectNode deleteCachedContentParametersToVertex( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_query", "pageSize"}, - Common.getValueByPath(fromObject, new String[] {"pageSize"})); + toObject, + new String[] {"_url", "name"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } - if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode deleteCachedContentResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listCachedContentsParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + ObjectNode deleteCachedContentResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - listCachedContentsConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToVertex( - ApiClient apiClient, 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"})); + 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 only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"fileUri"}, + Common.getValueByPath(fromObject, new String[] {"fileUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode blobToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + ObjectNode functionCallToMldev(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[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"args"}, + Common.getValueByPath(fromObject, new String[] {"args"})); } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"partialArgs"}))) { + throw new IllegalArgumentException( + "partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - 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[] {"willContinue"}))) { + throw new IllegalArgumentException( + "willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + ObjectNode functionCallingConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"allowedFunctionNames"}, + Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + new String[] {"mode"}, + Common.getValueByPath(fromObject, new String[] {"mode"})); } - 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[] {"streamFunctionCallArguments"}))) { + throw new IllegalArgumentException( + "streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent" + + " Platform mode, not in Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode partToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + ObjectNode getCachedContentParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + new String[] {"_url", "name"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != 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[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + new String[] {"_url", "name"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode googleMapsToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"authConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"inlineData"}, - blobToVertex( - apiClient, + new String[] {"authConfig"}, + authConfigToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), + Common.getValueByPath(fromObject, new String[] {"authConfig"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableWidget"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileData"}, - fileDataToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + new String[] {"enableWidget"}, + Common.getValueByPath(fromObject, new String[] {"enableWidget"})); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"searchTypes"}) != null) { Common.setValueByPath( toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + new String[] {"searchTypes"}, + Common.getValueByPath(fromObject, new String[] {"searchTypes"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"blockingConfidence"}))) { + throw new IllegalArgumentException( + "blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"excludeDomains"}))) { + throw new IllegalArgumentException( + "excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + new String[] {"timeRangeFilter"}, + Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listCachedContentsConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + parentObject, + new String[] {"_query", "pageSize"}, + Common.getValueByPath(fromObject, new String[] {"pageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + parentObject, + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentToVertex(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(); + ObjectNode listCachedContentsConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); - for (JsonNode item : keyArray) { - result.add(partToVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); + 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[] {"role"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( - toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + parentObject, + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToVertex( - 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."); + ObjectNode listCachedContentsParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + listCachedContentsConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listCachedContentsParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + listCachedContentsConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listCachedContentsResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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[] {"parameters"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { Common.setValueByPath( toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); + new String[] {"nextPageToken"}, + Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"cachedContents"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); + new String[] {"cachedContents"}, + Common.getValueByPath(fromObject, new String[] {"cachedContents"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { + ObjectNode listCachedContentsResponseFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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[] {"nextPageToken"}) != null) { Common.setValueByPath( toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); + new String[] {"nextPageToken"}, + Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToVertex( - 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[] {"cachedContents"}) != null) { Common.setValueByPath( toObject, - new String[] {"timeRangeFilter"}, - intervalToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); + new String[] {"cachedContents"}, + Common.getValueByPath(fromObject, new String[] {"cachedContents"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); + new String[] {"codeExecutionResult"}, + Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"executableCode"}, + Common.getValueByPath(fromObject, new String[] {"executableCode"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToVertex( - apiClient, + new String[] {"fileData"}, + fileDataToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), + Common.getValueByPath(fromObject, new String[] {"fileData"})), toObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode enterpriseWebSearchToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode apiKeyConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyString"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"apiKeyString"}, - Common.getValueByPath(fromObject, new String[] {"apiKeyString"})); + new String[] {"functionCall"}, + functionCallToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"functionCall"})), + toObject)); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"functionResponse"}, + Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode authConfigToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { Common.setValueByPath( toObject, - new String[] {"apiKeyConfig"}, - apiKeyConfigToVertex( - apiClient, + new String[] {"inlineData"}, + blobToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"})), + Common.getValueByPath(fromObject, new String[] {"inlineData"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"authType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( toObject, - new String[] {"authType"}, - Common.getValueByPath(fromObject, new String[] {"authType"})); + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleServiceAccountConfig"}, - Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"})); + new String[] {"thought"}, + Common.getValueByPath(fromObject, new String[] {"thought"})); } - if (Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { Common.setValueByPath( toObject, - new String[] {"httpBasicAuthConfig"}, - Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"})); + new String[] {"thoughtSignature"}, + Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); } - if (Common.getValueByPath(fromObject, new String[] {"oauthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"oauthConfig"}, - Common.getValueByPath(fromObject, new String[] {"oauthConfig"})); + new String[] {"videoMetadata"}, + Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); } - if (Common.getValueByPath(fromObject, new String[] {"oidcConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"oidcConfig"}, - Common.getValueByPath(fromObject, new String[] {"oidcConfig"})); + new String[] {"toolCall"}, + Common.getValueByPath(fromObject, new String[] {"toolCall"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleMapsToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"authConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"authConfig"}, - authConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"authConfig"})), - toObject)); + new String[] {"toolResponse"}, + Common.getValueByPath(fromObject, new String[] {"toolResponse"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"partMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"partMetadata"}, + Common.getValueByPath(fromObject, new String[] {"partMetadata"})); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode toolToVertex(ApiClient apiClient, 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"retrieval"}) != null) { + ObjectNode partToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( - toObject, - new String[] {"retrieval"}, - Common.getValueByPath(fromObject, new String[] {"retrieval"})); + toObject, + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleSearch"}, - googleSearchToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); + new String[] {"codeExecutionResult"}, + Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - toObject)); + new String[] {"executableCode"}, + Common.getValueByPath(fromObject, new String[] {"executableCode"})); } - if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { Common.setValueByPath( toObject, - new String[] {"enterpriseWebSearch"}, - enterpriseWebSearchToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})), - toObject)); + new String[] {"fileData"}, + Common.getValueByPath(fromObject, new String[] {"fileData"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleMaps"}, - googleMapsToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleMaps"})), - toObject)); + new String[] {"functionCall"}, + Common.getValueByPath(fromObject, new String[] {"functionCall"})); } - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlContext"}, - urlContextToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), - toObject)); + new String[] {"functionResponse"}, + Common.getValueByPath(fromObject, new String[] {"functionResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + new String[] {"inlineData"}, + Common.getValueByPath(fromObject, new String[] {"inlineData"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionCallingConfigToVertex( - 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[] {"text"}) != null) { Common.setValueByPath( toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - if (Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { Common.setValueByPath( toObject, - new String[] {"allowedFunctionNames"}, - Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); + new String[] {"thought"}, + Common.getValueByPath(fromObject, new String[] {"thought"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode latLngToVertex(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[] {"thoughtSignature"}) != null) { Common.setValueByPath( toObject, - new String[] {"latitude"}, - Common.getValueByPath(fromObject, new String[] {"latitude"})); + new String[] {"thoughtSignature"}, + Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); } - if (Common.getValueByPath(fromObject, new String[] {"longitude"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"longitude"}, - Common.getValueByPath(fromObject, new String[] {"longitude"})); + new String[] {"videoMetadata"}, + Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"toolCall"}))) { + throw new IllegalArgumentException( + "toolCall parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode retrievalConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latLng"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"latLng"}, - latLngToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"latLng"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"toolResponse"}))) { + throw new IllegalArgumentException( + "toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); } - 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[] {"partMetadata"}))) { + throw new IllegalArgumentException( + "partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode toolConfigToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode toolConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"retrievalConfig"}, + Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})); + } + if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { Common.setValueByPath( toObject, new String[] {"functionCallingConfig"}, - functionCallingConfigToVertex( - apiClient, + functionCallingConfigToMldev( JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeServerSideToolInvocations"}) + != null) { Common.setValueByPath( toObject, - new String[] {"retrievalConfig"}, - retrievalConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})), - toObject)); + new String[] {"includeServerSideToolInvocations"}, + Common.getValueByPath(fromObject, new String[] {"includeServerSideToolInvocations"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createCachedContentConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { + ObjectNode toolConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"ttl"}, - Common.getValueByPath(fromObject, new String[] {"ttl"})); + toObject, + new String[] {"retrievalConfig"}, + Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"expireTime"}, - Common.getValueByPath(fromObject, new String[] {"expireTime"})); + toObject, + new String[] {"functionCallingConfig"}, + Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"includeServerSideToolInvocations"}))) { + throw new IllegalArgumentException( + "includeServerSideToolInvocations parameter is only supported in Gemini Developer API" + + " mode, not in Gemini Enterprise Agent Platform mode."); } - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tContents( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + return toObject; + } - for (JsonNode item : keyArray) { - result.add(contentToVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"contents"}, result); + @ExcludeFromGeneratedCoverageReport + ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { + throw new IllegalArgumentException( + "retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"systemInstruction"}, - contentToVertex( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tContent( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); + toObject, + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); } - 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"tools"}, result); + if (Common.getValueByPath(fromObject, new String[] {"fileSearch"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"fileSearch"}, + Common.getValueByPath(fromObject, new String[] {"fileSearch"})); } - if (Common.getValueByPath(fromObject, new String[] {"toolConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"toolConfig"}, - toolConfigToVertex( - apiClient, + toObject, + new String[] {"googleSearch"}, + googleSearchToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolConfig"})), + Common.getValueByPath(fromObject, new String[] {"googleSearch"})), 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) { + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { Common.setValueByPath( toObject, - new String[] {"model"}, - Transformers.tCachesModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"googleMaps"}, + googleMapsToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"googleMaps"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - createCachedContentConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { + throw new IllegalArgumentException( + "enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode getCachedContentParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tCachedContentName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"parallelAiSearch"}))) { + throw new IllegalArgumentException( + "parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteCachedContentParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tCachedContentName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mcpServers"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"mcpServers"}, + Common.getValueByPath(fromObject, new String[] {"mcpServers"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listCachedContentsConfigToVertex( - 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) { + ObjectNode toolToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"retrieval"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); + toObject, + new String[] {"retrieval"}, + Common.getValueByPath(fromObject, new String[] {"retrieval"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listCachedContentsParametersToVertex( - 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[] {"computerUse"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - listCachedContentsConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"fileSearch"}))) { + throw new IllegalArgumentException( + "fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode cachedContentFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"googleSearch"}, + Common.getValueByPath(fromObject, new String[] {"googleSearch"})); } - 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[] {"codeExecution"}) != null) { Common.setValueByPath( toObject, - new String[] {"model"}, - Common.getValueByPath(fromObject, new String[] {"model"})); + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); } - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); + new String[] {"enterpriseWebSearch"}, + Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})); } - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { Common.setValueByPath( toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"updateTime"})); + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); } - if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"expireTime"}, - Common.getValueByPath(fromObject, new String[] {"expireTime"})); + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); } - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"parallelAiSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"usageMetadata"}, - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); + new String[] {"parallelAiSearch"}, + Common.getValueByPath(fromObject, new String[] {"parallelAiSearch"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteCachedContentResponseFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listCachedContentsResponseFromMldev( - 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[] {"urlContext"}) != null) { Common.setValueByPath( toObject, - new String[] {"nextPageToken"}, - Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); } - 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"cachedContents"}, result); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"mcpServers"}))) { + throw new IllegalArgumentException( + "mcpServers parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode cachedContentFromVertex( - 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"})); - } + ObjectNode updateCachedContentConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"ttl"}) != null) { Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + parentObject, + new String[] {"ttl"}, + Common.getValueByPath(fromObject, new String[] {"ttl"})); } - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { Common.setValueByPath( - toObject, - new String[] {"model"}, - Common.getValueByPath(fromObject, new String[] {"model"})); + parentObject, + new String[] {"expireTime"}, + Common.getValueByPath(fromObject, new String[] {"expireTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode updateCachedContentConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + 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( + ObjectNode updateCachedContentParametersToMldev( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + 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( + ObjectNode updateCachedContentParametersToVertex( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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(apiClient, 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(); @@ -1801,32 +1320,102 @@ 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(); } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } + + /** 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); + } + + /** + * 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) { + BuiltRequest builtRequest = buildRequestForCreate(model, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + "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(); + + 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 = cachedContentFromVertex(this.apiClient, responseNode, null); + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = getCachedContentParametersToVertex(this.apiClient, parameterNode, null); + path = Common.formatMap("{name}", body.get("_url")); + } else { + body = getCachedContentParametersToMldev(this.apiClient, parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{name}", body.get("_url")); } else { - responseNode = cachedContentFromMldev(this.apiClient, responseNode, null); + path = "{name}"; } - return JsonSerializable.fromJsonNode(responseNode, CachedContent.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); + } + + /** 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); } /** @@ -1837,8 +1426,20 @@ public CachedContent create(String model, CreateCachedContentConfig config) { * @return A {@link CachedContent} object that contains the info of the cached content. */ public CachedContent get(String name, GetCachedContentConfig config) { + BuiltRequest builtRequest = buildRequestForGet(name, config); - GetCachedContentParameters.Builder parameterBuilder = GetCachedContentParameters.builder(); + 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(); if (!Common.isZero(name)) { parameterBuilder.name(name); @@ -1851,10 +1452,10 @@ public CachedContent get(String name, GetCachedContentConfig config) { ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = getCachedContentParametersToVertex(this.apiClient, parameterNode, null); + body = deleteCachedContentParametersToVertex(this.apiClient, parameterNode, null); path = Common.formatMap("{name}", body.get("_url")); } else { - body = getCachedContentParametersToMldev(this.apiClient, parameterNode, null); + body = deleteCachedContentParametersToMldev(this.apiClient, parameterNode, null); if (body.get("_url") != null) { path = Common.formatMap("{name}", body.get("_url")); } else { @@ -1870,32 +1471,46 @@ 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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } 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(this.apiClient, responseNode, null); - } else { - responseNode = cachedContentFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, CachedContent.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(); } /** @@ -1905,9 +1520,20 @@ public CachedContent get(String name, GetCachedContentConfig config) { * @param config A {@link DeleteCachedContentConfig} for configuring the delete request. */ public DeleteCachedContentResponse delete(String name, DeleteCachedContentConfig config) { + BuiltRequest builtRequest = buildRequestForDelete(name, config); - DeleteCachedContentParameters.Builder parameterBuilder = - DeleteCachedContentParameters.builder(); + 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(); if (!Common.isZero(name)) { parameterBuilder.name(name); @@ -1920,10 +1546,10 @@ public DeleteCachedContentResponse delete(String name, DeleteCachedContentConfig ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = deleteCachedContentParametersToVertex(this.apiClient, parameterNode, null); + body = updateCachedContentParametersToVertex(this.apiClient, parameterNode, null); path = Common.formatMap("{name}", body.get("_url")); } else { - body = deleteCachedContentParametersToMldev(this.apiClient, parameterNode, null); + body = updateCachedContentParametersToMldev(this.apiClient, parameterNode, null); if (body.get("_url") != null) { path = Common.formatMap("{name}", body.get("_url")); } else { @@ -1939,35 +1565,48 @@ 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(); } + 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( - "delete", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = deleteCachedContentResponseFromVertex(this.apiClient, responseNode, null); - } else { - responseNode = deleteCachedContentResponseFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, DeleteCachedContentResponse.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(); @@ -1979,10 +1618,10 @@ ListCachedContentsResponse privateList(ListCachedContentsConfig config) { ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = listCachedContentsParametersToVertex(this.apiClient, parameterNode, null); + body = listCachedContentsParametersToVertex(parameterNode, null); path = Common.formatMap("cachedContents", body.get("_url")); } else { - body = listCachedContentsParametersToMldev(this.apiClient, parameterNode, null); + body = listCachedContentsParametersToMldev(parameterNode, null); if (body.get("_url") != null) { path = Common.formatMap("cachedContents", body.get("_url")); } else { @@ -1998,31 +1637,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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = listCachedContentsResponseFromVertex(this.apiClient, responseNode, null); - } else { - responseNode = listCachedContentsResponseFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, ListCachedContentsResponse.class); + "get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateList(response, config); } } @@ -2035,6 +1698,9 @@ ListCachedContentsResponse privateList(ListCachedContentsConfig config) { */ @SuppressWarnings("PatternMatchingInstanceof") public Pager list(ListCachedContentsConfig config) { + if (config == null) { + config = ListCachedContentsConfig.builder().build(); + } Function request = requestConfig -> { if (!(requestConfig instanceof ListCachedContentsConfig)) { 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/ChatBase.java b/src/main/java/com/google/genai/ChatBase.java index f33d6dc8e9e..79e58898d88 100644 --- a/src/main/java/com/google/genai/ChatBase.java +++ b/src/main/java/com/google/genai/ChatBase.java @@ -37,8 +37,8 @@ class ChatBase { private static final Logger logger = Logger.getLogger(ChatBase.class.getName()); ChatBase(List comprehensiveHistory, List curatedHistory) { - this.comprehensiveHistory = new ArrayList<>(); - this.curatedHistory = new ArrayList<>(); + this.comprehensiveHistory = comprehensiveHistory; + this.curatedHistory = curatedHistory; } /** @@ -175,13 +175,13 @@ public ImmutableList getHistory(boolean curated) { } } - private Content aggregateStreamingResponse(List responseChunks) { + private List aggregateStreamingResponse(List responseChunks) { + List aggregatedContents = new ArrayList<>(); if (responseChunks == null || responseChunks.isEmpty()) { - return Content.builder().build(); + return aggregatedContents; } - List aggregatedParts = new ArrayList<>(); String aggregatedText = ""; for (GenerateContentResponse responseChunk : responseChunks) { @@ -189,32 +189,11 @@ private Content aggregateStreamingResponse(List respons continue; } Candidate candidate = responseChunk.candidates().get().get(0); - if (candidate.content().isPresent() && candidate.content().get().parts().isPresent()) { - List parts = candidate.content().get().parts().get(); - for (Part part : parts) { - if (part.text().isPresent()) { - aggregatedText += part.text().get(); - } else { - boolean hasOtherContentParts = - part.functionCall().isPresent() - || part.functionResponse().isPresent() - || part.codeExecutionResult().isPresent() - || part.executableCode().isPresent() - || part.fileData().isPresent() - || part.videoMetadata().isPresent() - || part.thought().isPresent() - || part.inlineData().isPresent(); - if (hasOtherContentParts) { - aggregatedParts.add(part); - } - } - } + if (candidate.content().isPresent()) { + aggregatedContents.add(candidate.content().get()); } } - - // Construct the final response - aggregatedParts.add(Part.fromText(aggregatedText)); - return Content.builder().parts(aggregatedParts).role("model").build(); + return aggregatedContents; } protected void checkStreamResponseAndUpdateHistory() { @@ -222,8 +201,9 @@ protected void checkStreamResponseAndUpdateHistory() { throwIfStreamNotConsumed(); List streamingResponseContents = new ArrayList<>(); streamingResponseContents.addAll(this.currentUserMessage); - Content aggregatedResponse = aggregateStreamingResponse(this.currentResponseStream.history); - streamingResponseContents.add(aggregatedResponse); + List aggregatedResponse = + aggregateStreamingResponse(this.currentResponseStream.history); + streamingResponseContents.addAll(aggregatedResponse); recordHistory( streamingResponseContents, Iterables.getLast(this.currentResponseStream.history)); } diff --git a/src/main/java/com/google/genai/Client.java b/src/main/java/com/google/genai/Client.java index ed4ae43b122..763d04507f8 100644 --- a/src/main/java/com/google/genai/Client.java +++ b/src/main/java/com/google/genai/Client.java @@ -19,65 +19,57 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.auth.oauth2.GoogleCredentials; -import com.google.genai.errors.GenAiIOException; +import com.google.common.collect.ImmutableMap; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.types.ClientOptions; import com.google.genai.types.HttpOptions; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; import java.util.Optional; +import java.util.logging.Logger; -/** Client class for GenAI. */ +/** Client class for GenAI. This class is thread-safe. */ public final class Client implements AutoCloseable { - private static Optional geminiBaseUrl = Optional.empty(); - private static Optional vertexBaseUrl = Optional.empty(); - - /** Returns the default environment variables for the client. */ - static Map defaultEnvironmentVariables() { - Map variables = new HashMap<>(); - String value; - value = System.getenv("GOOGLE_GENAI_USE_VERTEXAI"); - if (value != null) { - variables.put("GOOGLE_GENAI_USE_VERTEXAI", value); - } - value = System.getenv("GOOGLE_GEMINI_BASE_URL"); - if (value != null) { - variables.put("GOOGLE_GEMINI_BASE_URL", value); - } - value = System.getenv("GOOGLE_VERTEX_BASE_URL"); - if (value != null) { - variables.put("GOOGLE_VERTEX_BASE_URL", value); - } - return variables; - } + private static final Logger logger = Logger.getLogger(Client.class.getName()); /** Async class for GenAI. */ public final class Async { public final AsyncModels models; + public final AsyncBatches batches; public final AsyncCaches caches; public final AsyncOperations operations; public final AsyncLive live; public final AsyncChats chats; public final AsyncFiles files; + public final AsyncTokens authTokens; + public final AsyncTunings tunings; + public final AsyncFileSearchStores fileSearchStores; public Async(ApiClient apiClient) { this.models = new AsyncModels(apiClient); + this.batches = new AsyncBatches(apiClient); this.caches = new AsyncCaches(apiClient); this.operations = new AsyncOperations(apiClient); this.live = new AsyncLive(apiClient); this.files = new AsyncFiles(apiClient); this.chats = new AsyncChats(apiClient); + this.authTokens = new AsyncTokens(apiClient); + this.tunings = new AsyncTunings(apiClient); + this.fileSearchStores = new AsyncFileSearchStores(apiClient); } } private final DebugConfig debugConfig; private final ApiClient apiClient; public final Models models; + public final Batches batches; public final Caches caches; public final Operations operations; public final Chats chats; public final Files files; public final Async async; + public final Tokens authTokens; + public final Tunings tunings; + public final FileSearchStores fileSearchStores; /** Builder for {@link Client}. */ public static class Builder { @@ -85,10 +77,11 @@ public static class Builder { private Optional project = Optional.empty(); private Optional location = Optional.empty(); private Optional credentials = Optional.empty(); + private Optional clientOptions = Optional.empty(); private Optional httpOptions = Optional.empty(); private Optional vertexAI = Optional.empty(); + private Optional enterprise = Optional.empty(); private Optional debugConfig = Optional.empty(); - private Optional> environmentVariables = Optional.empty(); /** Builds the {@link Client} instance. */ public Client build() { @@ -98,12 +91,14 @@ public Client build() { location, credentials, httpOptions, + clientOptions, vertexAI, - debugConfig, - environmentVariables); + enterprise, + debugConfig); } /** Sets the API key for Gemini API. */ + @CanIgnoreReturnValue public Builder apiKey(String apiKey) { checkNotNull(apiKey, "apiKey cannot be null"); this.apiKey = Optional.of(apiKey); @@ -111,6 +106,7 @@ public Builder apiKey(String apiKey) { } /** Sets the project ID for Vertex AI APIs. */ + @CanIgnoreReturnValue public Builder project(String project) { checkNotNull(project, "project cannot be null"); this.project = Optional.of(project); @@ -118,6 +114,7 @@ public Builder project(String project) { } /** Sets the location for Vertex AI APIs. */ + @CanIgnoreReturnValue public Builder location(String location) { checkNotNull(location, "location cannot be null"); this.location = Optional.of(location); @@ -125,20 +122,40 @@ public Builder location(String location) { } /** Sets the {@link GoogleCredentials} for Vertex AI APIs. */ + @CanIgnoreReturnValue public Builder credentials(GoogleCredentials credentials) { checkNotNull(credentials, "credentials cannot be null"); this.credentials = Optional.of(credentials); return this; } + /** Sets the {@link ClientOptions} for the API client. */ + @CanIgnoreReturnValue + public Builder clientOptions(ClientOptions clientOptions) { + checkNotNull(clientOptions, "clientOptions cannot be null"); + this.clientOptions = Optional.of(clientOptions); + return this; + } + /** Sets the {@link HttpOptions} for the API client. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions httpOptions) { checkNotNull(httpOptions, "httpOptions cannot be null"); this.httpOptions = Optional.of(httpOptions); return this; } + /** Sets whether to use Gemini Enterprise Agent Platform. + * When both enterprise and vertexAI are set, and they have different values, an IllegalArgumentException will be thrown. + */ + @CanIgnoreReturnValue + public Builder enterprise(boolean enterprise) { + this.enterprise = Optional.of(enterprise); + return this; + } + /** Sets whether to use Vertex AI APIs. */ + @CanIgnoreReturnValue public Builder vertexAI(boolean vertexAI) { this.vertexAI = Optional.of(vertexAI); return this; @@ -148,17 +165,12 @@ public Builder vertexAI(boolean vertexAI) { * Sets the {@link DebugConfig} for debugging or testing the Client. This is for internal use * only. */ + @CanIgnoreReturnValue Builder debugConfig(DebugConfig debugConfig) { checkNotNull(debugConfig, "debugConfig cannot be null"); this.debugConfig = Optional.of(debugConfig); return this; } - - /** Sets the environment variables for the API client. This is for internal use only. */ - Builder environmentVariables(Map environmentVariables) { - this.environmentVariables = Optional.of(environmentVariables); - return this; - } } /** Returns a {@link Builder} for {@link Client}. */ @@ -174,26 +186,29 @@ public Client() { /* location= */ Optional.empty(), /* credentials= */ Optional.empty(), /* httpOptions= */ Optional.empty(), + /* clientOptions= */ Optional.empty(), /* vertexAI= */ Optional.empty(), - /* debugConfig= */ Optional.empty(), - /* environmentVariables= */ Optional.empty()); + /* enterprise= */ Optional.empty(), + /* debugConfig= */ Optional.empty()); } /** * Constructs a Client instance with the given parameters. * - * @param apiKey Optional String for the API key. - * Gemini API only. - * @param project Optional String for the project ID. Vertex AI APIs only. - * Find your project ID - * @param location Optional String for the location. + * @param apiKey Optional String for the API key. Gemini API only. + * @param project Optional String for the project ID. Vertex AI APIs only. Find your project + * ID + * @param location Optional String for the location. * Vertex AI APIs only. * @param credentials Optional {@link GoogleCredentials}. Vertex AI APIs only. * @param httpOptions Optional {@link HttpOptions} for sending HTTP requests. + * @param clientOptions Optional {@link ClientOptions} for the API client. * @param vertexAI Optional Boolean for whether to use Vertex AI APIs. If not specified here nor * in the environment variable, default to false. * @param debugConfig Optional {@link DebugConfig} for debugging or testing the Client. - * @param environmentVariables Optional Map of environment variables. * @throws IllegalArgumentException if the project/location and API key are set together. */ private Client( @@ -202,21 +217,44 @@ private Client( Optional location, Optional credentials, Optional httpOptions, + Optional clientOptions, Optional vertexAI, - Optional debugConfig, - Optional> environmentVariables) { + Optional enterprise, + Optional debugConfig) { checkNotNull(vertexAI, "vertexAI cannot be null"); + checkNotNull(enterprise, "enterprise cannot be null"); checkNotNull(debugConfig, "debugConfig cannot be null"); - if (!environmentVariables.isPresent()) { - environmentVariables = Optional.of(defaultEnvironmentVariables()); + + if (enterprise.isPresent() && vertexAI.isPresent() && !enterprise.get().equals(vertexAI.get())) { + throw new IllegalArgumentException( + "enterprise and vertexAI flags have conflicting values, please set enterprise value only."); } boolean useVertexAI; - if (vertexAI.isPresent()) { + if (enterprise.isPresent()) { + useVertexAI = enterprise.get(); + } else if (vertexAI.isPresent()) { useVertexAI = vertexAI.get(); } else { - String envVar = environmentVariables.get().get("GOOGLE_GENAI_USE_VERTEXAI"); - useVertexAI = envVar != null && envVar.equalsIgnoreCase("true"); + ImmutableMap envVars = ApiClient.defaultEnvironmentVariables(); + String enterpriseEnv = envVars.get("enterprise"); + String vertexEnv = envVars.get("vertexAI"); + + boolean enterpriseEnvPresent = enterpriseEnv != null; + boolean vertexEnvPresent = vertexEnv != null; + + if (enterpriseEnvPresent && vertexEnvPresent && !enterpriseEnv.equalsIgnoreCase(vertexEnv)) { + logger.warning( + "Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."); + } + + if (enterpriseEnvPresent) { + useVertexAI = enterpriseEnv.equalsIgnoreCase("true"); + } else if (vertexEnvPresent) { + useVertexAI = vertexEnv.equalsIgnoreCase("true"); + } else { + useVertexAI = false; + } } if (project.isPresent() || location.isPresent()) { @@ -229,64 +267,59 @@ private Client( } } - // TODO(jayceeli): Remove this check once we support EasyGCP. - if (apiKey.isPresent() && useVertexAI) { - throw new IllegalArgumentException("Vertex AI APIs do not support API key."); - } - - Optional baseUrl = Client.inferBaseUrl(useVertexAI, httpOptions, environmentVariables); - if (baseUrl.isPresent()) { - if (httpOptions.isPresent()) { - httpOptions = Optional.of(httpOptions.get().toBuilder().baseUrl(baseUrl.get()).build()); - } else { - httpOptions = Optional.of(HttpOptions.builder().baseUrl(baseUrl.get()).build()); - } - } - this.debugConfig = debugConfig.orElse(new DebugConfig()); - if (this.debugConfig.clientMode().equals("replay") - || this.debugConfig.clientMode().equals("auto")) { - System.out.println("Instantialing a client that will use Replay mode..."); + if (this.debugConfig.clientMode().equals("replay")) { if (!useVertexAI) { - System.out.println("Instantialing a replay client that will use Gemini API..."); this.apiClient = new ReplayApiClient( /* apiKey= */ apiKey, /* httpOptions= */ httpOptions, + /* clientOptions= */ clientOptions, this.debugConfig.replaysDirectory(), this.debugConfig.replayId(), this.debugConfig.clientMode()); } else { - System.out.println("Instantialing a replay client that will use Vertex AI APIs..."); this.apiClient = new ReplayApiClient( + /* apiKey= */ apiKey, /* project= */ project, /* location= */ location, /* credentials= */ credentials, /* httpOptions= */ httpOptions, + /* clientOptions= */ clientOptions, this.debugConfig.replaysDirectory(), this.debugConfig.replayId(), this.debugConfig.clientMode()); } } else { if (!useVertexAI) { - this.apiClient = new HttpApiClient(/* apiKey= */ apiKey, /* httpOptions= */ httpOptions); + this.apiClient = + new HttpApiClient( + /* apiKey= */ apiKey, + /* httpOptions= */ httpOptions, + /* clientOptions= */ clientOptions); } else { this.apiClient = new HttpApiClient( + /* apiKey= */ apiKey, /* project= */ project, /* location= */ location, /* credentials= */ credentials, - /* httpOptions= */ httpOptions); + /* httpOptions= */ httpOptions, + /* clientOptions= */ clientOptions); } } models = new Models(this.apiClient); + batches = new Batches(this.apiClient); caches = new Caches(apiClient); operations = new Operations(this.apiClient); chats = new Chats(this.apiClient); async = new Async(this.apiClient); files = new Files(this.apiClient); + authTokens = new Tokens(this.apiClient); + tunings = new Tunings(this.apiClient); + fileSearchStores = new FileSearchStores(this.apiClient); } /** Returns whether the client is using Vertex AI APIs. */ @@ -294,6 +327,11 @@ public boolean vertexAI() { return apiClient.vertexAI(); } + /** Returns whether the client is using Gemini Enterprise Agent Platform. */ + public boolean enterprise() { + return apiClient.vertexAI(); + } + /** Returns the project ID for Vertex AI APIs. */ public String project() { return apiClient.project(); @@ -309,7 +347,8 @@ public String apiKey() { return apiClient.apiKey(); } - protected void setReplayId(String replayId) { + /** Sets the replay ID for the replay client. For internal testing only. */ + void setReplayId(String replayId) { if (this.apiClient instanceof ReplayApiClient) { ((ReplayApiClient) this.apiClient).initializeReplaySession(replayId); } @@ -320,7 +359,7 @@ DebugConfig debugConfig() { return debugConfig; } - /** Returns the client mode. If it's "replay" or "auto", then the client is in testing mode. */ + /** Returns the client mode. If it's "replay", then the client is in testing mode. */ String clientMode() { return debugConfig.clientMode(); } @@ -336,56 +375,25 @@ Optional baseUrl() { /** Closes the Client instance together with its instantiated http client. */ @Override public void close() { - try { - apiClient.httpClient().close(); - } catch (IOException e) { - throw new GenAiIOException("Failed to close the HTTP client.", e); - } + apiClient.close(); } /** - * Overrides the base URLs for the Gemini API and Vertex AI API. + * Overrides the base URLs for the Gemini API and/or Vertex AI API. * *

    Note: This function should be called before initializing the SDK. If the base URLs are set * after initializing the SDK, the base URLs will not be updated. - */ - public static void setDefaultBaseUrls( - Optional geminiBaseUrl, Optional vertexBaseUrl) { - Client.geminiBaseUrl = geminiBaseUrl; - Client.vertexBaseUrl = vertexBaseUrl; - } - - /** - * Returns the base URL for the Gemini API or Vertex AI API based on the following priority. + * + *

    Precedence rule for base URL: * *

    1. Base URL set via HttpOptions. * *

    2. Base URL set via the latest call to setDefaultBaseUrls. * - *

    3. Base URL set via environment variables. + *

    3. Base URL set via environment variables GOOGLE_GEMINI_BASE_URL or GOOGLE_VERTEX_BASE_URL. */ - static Optional inferBaseUrl( - boolean vertexAI, - Optional httpOptions, - Optional> environmentVariables) { - if (httpOptions.isPresent() && httpOptions.get().baseUrl().isPresent()) { - return httpOptions.get().baseUrl(); - } - - if (vertexAI) { - if (Client.vertexBaseUrl.isPresent()) { - return Client.vertexBaseUrl; - } else if (environmentVariables.isPresent()) { - return Optional.ofNullable(environmentVariables.get().get("GOOGLE_VERTEX_BASE_URL")); - } - } else { - if (Client.geminiBaseUrl.isPresent()) { - return Client.geminiBaseUrl; - } else if (environmentVariables.isPresent()) { - return Optional.ofNullable(environmentVariables.get().get("GOOGLE_GEMINI_BASE_URL")); - } - } - - return Optional.empty(); + public static void setDefaultBaseUrls( + Optional geminiBaseUrl, Optional vertexBaseUrl) { + ApiClient.setDefaultBaseUrls(geminiBaseUrl, vertexBaseUrl); } } diff --git a/src/main/java/com/google/genai/Common.java b/src/main/java/com/google/genai/Common.java index 873e2bb33d5..df84ea9ae02 100644 --- a/src/main/java/com/google/genai/Common.java +++ b/src/main/java/com/google/genai/Common.java @@ -19,6 +19,9 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.api.core.InternalApi; +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 +29,42 @@ 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 { +@InternalApi +public final class Common { private Common() {} + /** A class that holds the path, body, and http options of an API request. */ + public static class BuiltRequest { + final String path; + final String body; + final Optional httpOptions; + + /** Constructor for BuiltRequest. */ + public BuiltRequest(String path, String body, Optional httpOptions) { + this.path = path; + this.body = body; + this.httpOptions = httpOptions; + } + + public String body() { + return body; + } + + public String path() { + return path; + } + + public Optional httpOptions() { + return httpOptions; + } + } + /** * Sets the value of an object by a path. * @@ -45,7 +75,7 @@ private Common() {} *

    setValueByPath({'a': {'b':[{'c': v1}, {'c': v2}]}}, ['a', 'b[]', 'd'], v3) -> {'a': {'b': * [{'c': v1, 'd': v3}, {'c': v2,'d': v3}]}} */ - static void setValueByPath(ObjectNode jsonObject, String[] path, Object value) { + public static void setValueByPath(ObjectNode jsonObject, String[] path, Object value) { if (path == null || path.length == 0) { throw new IllegalArgumentException("Path cannot be empty."); } @@ -101,7 +131,14 @@ static void setValueByPath(ObjectNode jsonObject, String[] path, Object value) { } } - currentObject.put(path[path.length - 1], JsonSerializable.toJsonNode(value)); + String keyToSet = path[path.length - 1]; + 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); + } } /** @@ -111,9 +148,21 @@ 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) { + public 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' + */ + public 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; @@ -124,7 +173,7 @@ static void setValueByPath(ObjectNode jsonObject, String[] path, Object value) { String key = keys[i]; if (currentObject == null) { - return null; + return defaultValue; } if (key.endsWith("[]")) { @@ -136,17 +185,19 @@ static void setValueByPath(ObjectNode jsonObject, String[] path, Object value) { if (keys.length - 1 == i) { return arrayNode; } - ArrayNode result = JsonSerializable.objectMapper.createArrayNode(); + 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); @@ -156,13 +207,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; } } } @@ -170,7 +221,7 @@ static void setValueByPath(ObjectNode jsonObject, String[] path, Object value) { return currentObject; } - static String formatMap(String template, JsonNode data) { + public static String formatMap(String template, JsonNode data) { if (data == null) { return template; } @@ -187,7 +238,7 @@ static String formatMap(String template, JsonNode data) { return template; } - static boolean isZero(Object obj) { + public static boolean isZero(Object obj) { if (obj == null) { return true; } @@ -231,7 +282,9 @@ public static String urlEncode(ObjectNode paramsNode) { if (valueNode.isNull()) { queryBuilder.add(encodedKey + "="); } else { - String encodedValue = URLEncoder.encode(valueNode.asText(""), utf8); + // In python(and replay files), "*" is encoded as "%2A" although it is not required. + // So we keep the same behavior here. + String encodedValue = URLEncoder.encode(valueNode.asText(""), utf8).replace("*", "%2A"); queryBuilder.add(encodedKey + "=" + encodedValue); } } @@ -240,4 +293,157 @@ public static String urlEncode(ObjectNode paramsNode) { } return queryBuilder.toString(); } + + /** Converts a snake_case string to camelCase. */ + public static String snakeToCamel(String str) { + if (str == null || str.isEmpty()) { + return str; + } + + StringBuilder sb = new StringBuilder(); + boolean capitalizeNext = false; + for (char c : str.toCharArray()) { + if (c == '_') { + capitalizeNext = true; + } else { + sb.append(capitalizeNext ? Character.toUpperCase(c) : c); + capitalizeNext = false; + } + } + 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}}]} + */ + public 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 + */ + public 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/Documents.java b/src/main/java/com/google/genai/Documents.java new file mode 100644 index 00000000000..609e52c460a --- /dev/null +++ b/src/main/java/com/google/genai/Documents.java @@ -0,0 +1,401 @@ +/* + * 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.node.ObjectNode; +import com.google.genai.Common.BuiltRequest; +import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.DeleteDocumentConfig; +import com.google.genai.types.DeleteDocumentParameters; +import com.google.genai.types.Document; +import com.google.genai.types.GetDocumentConfig; +import com.google.genai.types.GetDocumentParameters; +import com.google.genai.types.HttpOptions; +import com.google.genai.types.ListDocumentsConfig; +import com.google.genai.types.ListDocumentsParameters; +import com.google.genai.types.ListDocumentsResponse; +import java.io.IOException; +import java.util.Optional; +import java.util.function.Function; +import okhttp3.ResponseBody; + +public final class Documents { + + final ApiClient apiClient; + + public Documents(ApiClient apiClient) { + this.apiClient = apiClient; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode deleteDocumentConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"force"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"_query", "force"}, + Common.getValueByPath(fromObject, new String[] {"force"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode deleteDocumentParametersToMldev(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"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + deleteDocumentConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode getDocumentParametersToMldev(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"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listDocumentsConfigToMldev(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 listDocumentsParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"parent"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "parent"}, + Common.getValueByPath(fromObject, new String[] {"parent"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + listDocumentsConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listDocumentsResponseFromMldev(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[] {"documents"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"documents"}, + Common.getValueByPath(fromObject, new String[] {"documents"})); + } + + return toObject; + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForGet(String name, GetDocumentConfig config) { + + GetDocumentParameters.Builder parameterBuilder = GetDocumentParameters.builder(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = getDocumentParametersToMldev(parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{name}", body.get("_url")); + } else { + path = "{name}"; + } + } + 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. */ + Document processResponseForGet(ApiResponse response, GetDocumentConfig 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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + return JsonSerializable.fromJsonNode(responseNode, Document.class); + } + + public Document get(String name, GetDocumentConfig 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, DeleteDocumentConfig config) { + + DeleteDocumentParameters.Builder parameterBuilder = DeleteDocumentParameters.builder(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = deleteDocumentParametersToMldev(parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{name}", body.get("_url")); + } else { + path = "{name}"; + } + } + 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); + } + + public void delete(String name, DeleteDocumentConfig config) { + BuiltRequest builtRequest = buildRequestForDelete(name, config); + + try (ApiResponse response = + this.apiClient.request( + "delete", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return; + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateList(String parent, ListDocumentsConfig config) { + + ListDocumentsParameters.Builder parameterBuilder = ListDocumentsParameters.builder(); + + if (!Common.isZero(parent)) { + parameterBuilder.parent(parent); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = listDocumentsParametersToMldev(parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{parent}/documents", body.get("_url")); + } else { + path = "{parent}/documents"; + } + } + 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. */ + ListDocumentsResponse processResponseForPrivateList( + ApiResponse response, ListDocumentsConfig 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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + if (!this.apiClient.vertexAI()) { + responseNode = listDocumentsResponseFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode(responseNode, ListDocumentsResponse.class); + } + + ListDocumentsResponse privateList(String parent, ListDocumentsConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateList(parent, config); + + try (ApiResponse response = + this.apiClient.request( + "get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateList(response, config); + } + } + + /** + * Makes an API request to list the available documents. + * + * @param parent The name of the RagStore containing the Documents. + * @param config A {@link ListDocumentsConfig} for configuring the list request. + * @return A {@link Pager} object that contains the list of documents. The pager is an iterable + * and automatically queries the next page once the current page is exhausted. + */ + @SuppressWarnings("PatternMatchingInstanceof") + public Pager list(String parent, ListDocumentsConfig config) { + if (config == null) { + config = ListDocumentsConfig.builder().build(); + } + Function request = + requestConfig -> { + if (!(requestConfig instanceof ListDocumentsConfig)) { + throw new GenAiIOException( + "Internal error: Pager expected ListDocumentsConfig but received " + + requestConfig.getClass().getName()); + } + return this.privateList(parent, (ListDocumentsConfig) requestConfig); + }; + return new Pager<>( + Pager.PagedItem.DOCUMENTS, + request, + (ObjectNode) JsonSerializable.toJsonNode(config), + JsonSerializable.toJsonNode(privateList(parent, config))); + } +} diff --git a/src/main/java/com/google/genai/FileSearchStores.java b/src/main/java/com/google/genai/FileSearchStores.java new file mode 100644 index 00000000000..96d9964e387 --- /dev/null +++ b/src/main/java/com/google/genai/FileSearchStores.java @@ -0,0 +1,1094 @@ +/* + * 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.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.CreateFileSearchStoreConfig; +import com.google.genai.types.CreateFileSearchStoreParameters; +import com.google.genai.types.DeleteFileSearchStoreConfig; +import com.google.genai.types.DeleteFileSearchStoreParameters; +import com.google.genai.types.DownloadMediaConfig; +import com.google.genai.types.FileSearchStore; +import com.google.genai.types.GetFileSearchStoreConfig; +import com.google.genai.types.GetFileSearchStoreParameters; +import com.google.genai.types.HttpOptions; +import com.google.genai.types.HttpResponse; +import com.google.genai.types.ImportFileConfig; +import com.google.genai.types.ImportFileOperation; +import com.google.genai.types.ImportFileParameters; +import com.google.genai.types.ListFileSearchStoresConfig; +import com.google.genai.types.ListFileSearchStoresParameters; +import com.google.genai.types.ListFileSearchStoresResponse; +import com.google.genai.types.UploadToFileSearchStoreConfig; +import com.google.genai.types.UploadToFileSearchStoreOperation; +import com.google.genai.types.UploadToFileSearchStoreParameters; +import com.google.genai.types.UploadToFileSearchStoreResumableResponse; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +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 FileSearchStores { + public final Documents documents; + + final ApiClient apiClient; + + private final UploadClient uploadClient; + + public FileSearchStores(ApiClient apiClient) { + this.apiClient = apiClient; + this.uploadClient = new UploadClient(apiClient); + this.documents = new Documents(apiClient); + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode createFileSearchStoreConfigToMldev( + ApiClient apiClient, 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[] {"embeddingModel"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"embeddingModel"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"embeddingModel"}))); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode createFileSearchStoreParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + createFileSearchStoreConfigToMldev( + apiClient, + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode deleteFileSearchStoreConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"force"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"_query", "force"}, + Common.getValueByPath(fromObject, new String[] {"force"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode deleteFileSearchStoreParametersToMldev(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"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + deleteFileSearchStoreConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode getFileSearchStoreParametersToMldev(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"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode importFileConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"customMetadata"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"customMetadata"}, + Common.getValueByPath(fromObject, new String[] {"customMetadata"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"chunkingConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"chunkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"chunkingConfig"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode importFileOperationFromMldev(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"}, + importFileResponseFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"response"})), + toObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode importFileParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"fileSearchStoreName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "file_search_store_name"}, + Common.getValueByPath(fromObject, new String[] {"fileSearchStoreName"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"fileName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"fileName"}, + Common.getValueByPath(fromObject, new String[] {"fileName"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + importFileConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode importFileResponseFromMldev(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[] {"parent"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"parent"}, + Common.getValueByPath(fromObject, new String[] {"parent"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"documentName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"documentName"}, + Common.getValueByPath(fromObject, new String[] {"documentName"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listFileSearchStoresConfigToMldev(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 listFileSearchStoresParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + listFileSearchStoresConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listFileSearchStoresResponseFromMldev(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[] {"fileSearchStores"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"fileSearchStores"}, + Common.getValueByPath(fromObject, new String[] {"fileSearchStores"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode uploadToFileSearchStoreConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); + } + + 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[] {"customMetadata"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"customMetadata"}, + Common.getValueByPath(fromObject, new String[] {"customMetadata"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"chunkingConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"chunkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"chunkingConfig"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode uploadToFileSearchStoreParametersToMldev( + JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"fileSearchStoreName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"_url", "file_search_store_name"}, + Common.getValueByPath(fromObject, new String[] {"fileSearchStoreName"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + uploadToFileSearchStoreConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode uploadToFileSearchStoreResumableResponseFromMldev( + 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; + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForCreate(CreateFileSearchStoreConfig config) { + + CreateFileSearchStoreParameters.Builder parameterBuilder = + CreateFileSearchStoreParameters.builder(); + + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = createFileSearchStoreParametersToMldev(this.apiClient, parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("fileSearchStores", body.get("_url")); + } else { + path = "fileSearchStores"; + } + } + 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. */ + FileSearchStore processResponseForCreate( + ApiResponse response, CreateFileSearchStoreConfig 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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + return JsonSerializable.fromJsonNode(responseNode, FileSearchStore.class); + } + + public FileSearchStore create(CreateFileSearchStoreConfig config) { + BuiltRequest builtRequest = buildRequestForCreate(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, GetFileSearchStoreConfig config) { + + GetFileSearchStoreParameters.Builder parameterBuilder = GetFileSearchStoreParameters.builder(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = getFileSearchStoreParametersToMldev(parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{name}", body.get("_url")); + } else { + path = "{name}"; + } + } + 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. */ + FileSearchStore processResponseForGet(ApiResponse response, GetFileSearchStoreConfig 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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + return JsonSerializable.fromJsonNode(responseNode, FileSearchStore.class); + } + + public FileSearchStore get(String name, GetFileSearchStoreConfig 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, DeleteFileSearchStoreConfig config) { + + DeleteFileSearchStoreParameters.Builder parameterBuilder = + DeleteFileSearchStoreParameters.builder(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = deleteFileSearchStoreParametersToMldev(parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{name}", body.get("_url")); + } else { + path = "{name}"; + } + } + 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); + } + + public void delete(String name, DeleteFileSearchStoreConfig config) { + BuiltRequest builtRequest = buildRequestForDelete(name, config); + + try (ApiResponse response = + this.apiClient.request( + "delete", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return; + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateList(ListFileSearchStoresConfig config) { + + ListFileSearchStoresParameters.Builder parameterBuilder = + ListFileSearchStoresParameters.builder(); + + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = listFileSearchStoresParametersToMldev(parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("fileSearchStores", body.get("_url")); + } else { + path = "fileSearchStores"; + } + } + 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. */ + ListFileSearchStoresResponse processResponseForPrivateList( + ApiResponse response, ListFileSearchStoresConfig 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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + if (!this.apiClient.vertexAI()) { + responseNode = listFileSearchStoresResponseFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode(responseNode, ListFileSearchStoresResponse.class); + } + + ListFileSearchStoresResponse privateList(ListFileSearchStoresConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateList(config); + + try (ApiResponse response = + this.apiClient.request( + "get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateList(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateUploadToFileSearchStore( + String fileSearchStoreName, UploadToFileSearchStoreConfig config) { + + UploadToFileSearchStoreParameters.Builder parameterBuilder = + UploadToFileSearchStoreParameters.builder(); + + if (!Common.isZero(fileSearchStoreName)) { + parameterBuilder.fileSearchStoreName(fileSearchStoreName); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = uploadToFileSearchStoreParametersToMldev(parameterNode, null); + if (body.get("_url") != null) { + path = + Common.formatMap( + "upload/v1beta/{file_search_store_name}:uploadToFileSearchStore", body.get("_url")); + } else { + path = "upload/v1beta/{file_search_store_name}:uploadToFileSearchStore"; + } + } + 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. */ + UploadToFileSearchStoreResumableResponse processResponseForPrivateUploadToFileSearchStore( + ApiResponse response, UploadToFileSearchStoreConfig 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 != null && config.shouldReturnHttpResponse().orElse(false)) { + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return UploadToFileSearchStoreResumableResponse.builder() + .sdkHttpResponse(HttpResponse.builder().body(responseString)) + .build(); + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return UploadToFileSearchStoreResumableResponse.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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + if (!this.apiClient.vertexAI()) { + responseNode = uploadToFileSearchStoreResumableResponseFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode( + responseNode, UploadToFileSearchStoreResumableResponse.class); + } + + UploadToFileSearchStoreResumableResponse privateUploadToFileSearchStore( + String fileSearchStoreName, UploadToFileSearchStoreConfig config) { + BuiltRequest builtRequest = + buildRequestForPrivateUploadToFileSearchStore(fileSearchStoreName, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateUploadToFileSearchStore(response, config); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForImportFile( + String fileSearchStoreName, String fileName, ImportFileConfig config) { + + ImportFileParameters.Builder parameterBuilder = ImportFileParameters.builder(); + + if (!Common.isZero(fileSearchStoreName)) { + parameterBuilder.fileSearchStoreName(fileSearchStoreName); + } + if (!Common.isZero(fileName)) { + parameterBuilder.fileName(fileName); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = importFileParametersToMldev(parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("{file_search_store_name}:importFile", body.get("_url")); + } else { + path = "{file_search_store_name}:importFile"; + } + } + 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. */ + ImportFileOperation processResponseForImportFile(ApiResponse response, ImportFileConfig 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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + if (!this.apiClient.vertexAI()) { + responseNode = importFileOperationFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode(responseNode, ImportFileOperation.class); + } + + public ImportFileOperation importFile( + String fileSearchStoreName, String fileName, ImportFileConfig config) { + BuiltRequest builtRequest = buildRequestForImportFile(fileSearchStoreName, fileName, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForImportFile(response, config); + } + } + + /** + * Makes an API request to list the available file search stores. + * + * @param config A {@link ListFileSearchStoresConfig} for configuring the list request. + * @return A {@link Pager} object that contains the list of file search stores. The pager is an + * iterable and automatically queries the next page once the current page is exhausted. + */ + @SuppressWarnings("PatternMatchingInstanceof") + public Pager list(ListFileSearchStoresConfig config) { + if (config == null) { + config = ListFileSearchStoresConfig.builder().build(); + } + Function request = + requestConfig -> { + if (!(requestConfig instanceof ListFileSearchStoresConfig)) { + throw new GenAiIOException( + "Internal error: Pager expected ListFileSearchStoresConfig but received " + + requestConfig.getClass().getName()); + } + return this.privateList((ListFileSearchStoresConfig) requestConfig); + }; + return new Pager<>( + Pager.PagedItem.FILE_SEARCH_STORES, + request, + (ObjectNode) JsonSerializable.toJsonNode(config), + JsonSerializable.toJsonNode(privateList(config))); + } + + static UploadToFileSearchStoreOperation operationFromResponse(ResponseBody responseBody) { + 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, UploadToFileSearchStoreOperation.class); + } + + private String getUploadUrl( + String fileSearchStoreName, + UploadToFileSearchStoreConfig config, + Optional mimeType, + Optional fileName, + long size) { + Optional mimeTypeToUse = + mimeType.isPresent() + ? mimeType + : Optional.ofNullable(config).flatMap(UploadToFileSearchStoreConfig::mimeType); + Optional userHttpOptions = + Optional.ofNullable(config).flatMap(UploadToFileSearchStoreConfig::httpOptions); + HttpOptions httpOptions = + UploadClient.buildResumableUploadHttpOptions( + userHttpOptions, mimeTypeToUse, fileName, size); + UploadToFileSearchStoreResumableResponse response = + privateUploadToFileSearchStore( + fileSearchStoreName, + UploadToFileSearchStoreConfig.builder() + .httpOptions(httpOptions) + .shouldReturnHttpResponse(true) + .build()); + + return response + .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 upload to file search store. Upload URL was not returned in the" + + " resumable response.")); + } + + /** + * Uploads a file to the file search store. + * + * @param fileSearchStoreName The name of the file search store to upload to. + * @param file The file to upload. + * @param config The configuration for the upload. + * @return The long running operation of uploading. + */ + public UploadToFileSearchStoreOperation uploadToFileSearchStore( + String fileSearchStoreName, java.io.File file, UploadToFileSearchStoreConfig 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) { + mimeType = Optional.of(probedMimeType); + } else { + mimeType = Optional.empty(); + } + String uploadUrl = + getUploadUrl(fileSearchStoreName, config, mimeType, Optional.of(fileName), size); + Optional httpOptions = config != null ? config.httpOptions() : Optional.empty(); + ResponseBody responseBody = uploadClient.upload(uploadUrl, inputStream, size, httpOptions); + return operationFromResponse(responseBody); + } catch (IOException e) { + throw new GenAiIOException("Failed to upload file.", e); + } + } + + /** + * Uploads a file in bytes format to the file search store. + * + * @param fileSearchStoreName The name of the file search store to upload to. + * @param bytes The bytes of the file to upload. + * @param config The configuration for the upload. + * @return The long running operation of uploading. + */ + public UploadToFileSearchStoreOperation uploadToFileSearchStore( + String fileSearchStoreName, byte[] bytes, UploadToFileSearchStoreConfig config) { + String uploadUrl = + getUploadUrl( + fileSearchStoreName, + config, + Optional.empty(), + Optional.empty(), + bytes.length); + Optional httpOptions = config != null ? config.httpOptions() : Optional.empty(); + ResponseBody responseBody = uploadClient.upload(uploadUrl, bytes, httpOptions); + return operationFromResponse(responseBody); + } + + /** + * Uploads a file as input stream to the API. + * + * @param fileSearchStoreName The name of the file search store to upload to. + * @param inputStream The input stream of the file to upload. + * @param size The size of the file to upload. + * @param config The configuration for the upload. + * @return The uploaded file. + */ + public UploadToFileSearchStoreOperation uploadToFileSearchStore( + String fileSearchStoreName, + InputStream inputStream, + long size, + UploadToFileSearchStoreConfig config) { + String uploadUrl = + getUploadUrl( + fileSearchStoreName, config, Optional.empty(), Optional.empty(), size); + Optional httpOptions = config != null ? config.httpOptions() : Optional.empty(); + ResponseBody responseBody = uploadClient.upload(uploadUrl, inputStream, size, httpOptions); + return operationFromResponse(responseBody); + } + + /** + * Uploads a file to the API. + * + * @param fileSearchStoreName The name of the file search store to upload to. + * @param filePath The path of the file to upload. + * @param config The configuration for the upload. + * @return The uploaded file. + */ + public UploadToFileSearchStoreOperation uploadToFileSearchStore( + String fileSearchStoreName, String filePath, UploadToFileSearchStoreConfig config) { + java.io.File file = new java.io.File(filePath); + return uploadToFileSearchStore(fileSearchStoreName, file, config); + } + + /** + * Downloads media using a Media ID or URI. This method is only supported in the Gemini Developer + * client. + * + * @param uri The URI or Media ID of the blob. + * @param config Optional configuration for the download. + * @return The blob data as a byte array. + */ + public byte[] downloadMedia(String uri, DownloadMediaConfig config) { + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client."); + } + java.util.Objects.requireNonNull(uri, "uri cannot be null"); + + java.net.URI parsedUri; + try { + parsedUri = new java.net.URI(uri); + } catch (java.net.URISyntaxException e) { + throw new IllegalArgumentException("Invalid uri format: " + uri, e); + } + + String path = parsedUri.getPath(); + if (path != null && path.startsWith("/")) { + path = path.substring(1); + } + + if (path == null) { + throw new IllegalArgumentException("Invalid uri format (no path): " + uri); + } + + if (!path.contains("/media/")) { + throw new IllegalArgumentException( + "Invalid uri format: " + uri + ". Expected to contain /media/"); + } + + String requestPath = path + "?alt=media"; + + Optional httpOptions = Optional.empty(); + if (config != null) { + httpOptions = config.httpOptions(); + } + + ApiResponse response = this.apiClient.request("get", requestPath, "", httpOptions); + try { + return response.getBody().bytes(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read blob content.", e); + } + } +} diff --git a/src/main/java/com/google/genai/Files.java b/src/main/java/com/google/genai/Files.java index 07c2b2f23a4..0898891e419 100644 --- a/src/main/java/com/google/genai/Files.java +++ b/src/main/java/com/google/genai/Files.java @@ -21,9 +21,11 @@ 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.auth.oauth2.GoogleCredentials; +import com.google.common.base.Ascii; +import com.google.common.collect.ImmutableMap; +import com.google.genai.Common.BuiltRequest; import com.google.genai.errors.GenAiIOException; import com.google.genai.types.CreateFileConfig; import com.google.genai.types.CreateFileParameters; @@ -38,9 +40,12 @@ import com.google.genai.types.GetFileParameters; import com.google.genai.types.HttpOptions; import com.google.genai.types.HttpResponse; +import com.google.genai.types.InternalRegisterFilesParameters; import com.google.genai.types.ListFilesConfig; import com.google.genai.types.ListFilesParameters; import com.google.genai.types.ListFilesResponse; +import com.google.genai.types.RegisterFilesConfig; +import com.google.genai.types.RegisterFilesResponse; import com.google.genai.types.UploadFileConfig; import com.google.genai.types.Video; import java.io.FileInputStream; @@ -48,12 +53,12 @@ import java.io.IOException; import java.io.InputStream; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.util.EntityUtils; +import okhttp3.Headers; +import okhttp3.ResponseBody; /** * Provides methods for interacting with the available GenAI files. Instantiating this class is not @@ -61,6 +66,7 @@ * `client.files.methodName(...)` directly. */ public final class Files { + final ApiClient apiClient; private final UploadClient uploadClient; @@ -71,431 +77,259 @@ public Files(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode listFilesConfigToMldev( - 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) { + ObjectNode createFileParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"file"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); + toObject, + new String[] {"file"}, + Common.getValueByPath(fromObject, new String[] {"file"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listFilesParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + ObjectNode createFileResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - listFilesConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileStatusToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"details"}) != null) { + ObjectNode deleteFileParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"details"}, - Common.getValueByPath(fromObject, new String[] {"details"})); + new String[] {"_url", "file"}, + Transformers.tFileName(Common.getValueByPath(fromObject, new String[] {"name"}))); } - if (Common.getValueByPath(fromObject, new String[] {"message"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"message"}, - Common.getValueByPath(fromObject, new String[] {"message"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"code"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode deleteFileResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode getFileParametersToMldev(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( - apiClient, - 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( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"file"}) != null) { + ObjectNode internalRegisterFilesParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"uris"}) != null) { Common.setValueByPath( toObject, - new String[] {"file"}, - fileToMldev( - apiClient, - JsonSerializable.toJsonNode(Common.getValueByPath(fromObject, new String[] {"file"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"uris"}, + Common.getValueByPath(fromObject, new String[] {"uris"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode getFileParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + ObjectNode listFilesConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( - toObject, - new String[] {"_url", "file"}, - Transformers.tFileName( - 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"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode deleteFileParametersToMldev( - 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", "file"}, - Transformers.tFileName( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"name"}))); - } - + ObjectNode listFilesParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + JsonNode unused = + listFilesConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileStatusFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"details"}) != null) { + ObjectNode listFilesResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"details"}, - Common.getValueByPath(fromObject, new String[] {"details"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"message"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { Common.setValueByPath( toObject, - new String[] {"message"}, - Common.getValueByPath(fromObject, new String[] {"message"})); + new String[] {"nextPageToken"}, + Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"code"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"files"}) != null) { Common.setValueByPath( toObject, - new String[] {"code"}, - Common.getValueByPath(fromObject, new String[] {"code"})); + new String[] {"files"}, + Common.getValueByPath(fromObject, new String[] {"files"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileFromMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + ObjectNode registerFilesResponseFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"files"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"files"}, + Common.getValueByPath(fromObject, new String[] {"files"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"sizeBytes"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"sizeBytes"}, - Common.getValueByPath(fromObject, new String[] {"sizeBytes"})); - } + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateList(ListFilesConfig config) { - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); - } + ListFilesParameters.Builder parameterBuilder = ListFilesParameters.builder(); - if (Common.getValueByPath(fromObject, new String[] {"expirationTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"expirationTime"}, - Common.getValueByPath(fromObject, new String[] {"expirationTime"})); + if (!Common.isZero(config)) { + parameterBuilder.config(config); } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"updateTime"})); + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = listFilesParametersToMldev(parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("files", body.get("_url")); + } else { + path = "files"; + } } + body.remove("_url"); - if (Common.getValueByPath(fromObject, new String[] {"sha256Hash"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"sha256Hash"}, - Common.getValueByPath(fromObject, new String[] {"sha256Hash"})); + JsonNode queryParams = body.get("_query"); + if (queryParams != null) { + body.remove("_query"); + path = String.format("%s?%s", path, Common.urlEncode((ObjectNode) queryParams)); } - if (Common.getValueByPath(fromObject, new String[] {"uri"}) != null) { - Common.setValueByPath( - toObject, new String[] {"uri"}, Common.getValueByPath(fromObject, new String[] {"uri"})); + // TODO: Remove the hack that removes config. + Optional requestHttpOptions = Optional.empty(); + if (config != null) { + requestHttpOptions = config.httpOptions(); } - if (Common.getValueByPath(fromObject, new String[] {"downloadUri"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"downloadUri"}, - Common.getValueByPath(fromObject, new String[] {"downloadUri"})); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - if (Common.getValueByPath(fromObject, new String[] {"state"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"state"}, - Common.getValueByPath(fromObject, new String[] {"state"})); + /** 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); } - if (Common.getValueByPath(fromObject, new String[] {"source"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"source"}, - Common.getValueByPath(fromObject, new String[] {"source"})); - } + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); } - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"error"}, - fileStatusFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"error"})), - toObject)); + if (!this.apiClient.vertexAI()) { + responseNode = listFilesResponseFromMldev(responseNode, null); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listFilesResponseFromMldev( - ApiClient apiClient, 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"})); + ListFilesResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, ListFilesResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; } - - 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"files"}, result); + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode createFileResponseFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); } - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteFileResponseFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ListFilesResponse privateList(ListFilesConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateList(config); - return toObject; + try (ApiResponse response = + this.apiClient.request( + "get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateList(response, config); + } } - /** - * 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 buildRequestForPrivateCreate(File file, CreateFileConfig config) { - ListFilesParameters.Builder parameterBuilder = ListFilesParameters.builder(); + CreateFileParameters.Builder parameterBuilder = CreateFileParameters.builder(); + if (!Common.isZero(file)) { + parameterBuilder.file(file); + } if (!Common.isZero(config)) { parameterBuilder.config(config); } @@ -504,13 +338,15 @@ ListFilesResponse privateList(ListFilesConfig config) { ObjectNode body; String path; if (this.apiClient.vertexAI()) { - throw new UnsupportedOperationException("This method is not supported by the Vertex AI."); + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); } else { - body = listFilesParametersToMldev(this.apiClient, parameterNode, null); + body = createFileParametersToMldev(parameterNode, null); if (body.get("_url") != null) { - path = Common.formatMap("files", body.get("_url")); + path = Common.formatMap("upload/v1beta/files", body.get("_url")); } else { - path = "files"; + path = "upload/v1beta/files"; } } body.remove("_url"); @@ -522,40 +358,73 @@ ListFilesResponse privateList(ListFilesConfig 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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } 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 not supported by the Vertex AI."); - } else { - responseNode = listFilesResponseFromMldev(this.apiClient, responseNode, null); + /** 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 != null && 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)); } - return JsonSerializable.fromJsonNode(responseNode, ListFilesResponse.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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + if (!this.apiClient.vertexAI()) { + responseNode = createFileResponseFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode(responseNode, CreateFileResponse.class); } CreateFileResponse privateCreate(File file, CreateFileConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateCreate(file, config); - CreateFileParameters.Builder parameterBuilder = CreateFileParameters.builder(); + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateCreate(response, config); + } + } - if (!Common.isZero(file)) { - parameterBuilder.file(file); + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForGet(String name, GetFileConfig config) { + + GetFileParameters.Builder parameterBuilder = GetFileParameters.builder(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); } if (!Common.isZero(config)) { parameterBuilder.config(config); @@ -565,13 +434,15 @@ CreateFileResponse privateCreate(File file, CreateFileConfig config) { ObjectNode body; String path; if (this.apiClient.vertexAI()) { - throw new UnsupportedOperationException("This method is not supported by the Vertex AI."); + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); } else { - body = createFileParametersToMldev(this.apiClient, parameterNode, null); + body = getFileParametersToMldev(parameterNode, null); if (body.get("_url") != null) { - path = Common.formatMap("upload/v1beta/files", body.get("_url")); + path = Common.formatMap("files/{file}", body.get("_url")); } else { - path = "upload/v1beta/files"; + path = "files/{file}"; } } body.remove("_url"); @@ -583,42 +454,33 @@ 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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); + } - if (config.shouldReturnHttpResponse().orElse(false)) { - Map headers = new HashMap<>(); - for (Header header : response.getHeaders()) { - headers.put(header.getName(), header.getValue()); - } - return CreateFileResponse.builder() - .sdkHttpResponse(HttpResponse.builder().headers(headers).body(responseString).build()) - .build(); - } + /** 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 not supported by the Vertex AI."); - } else { - responseNode = createFileResponseFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, CreateFileResponse.class); + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); } + + return JsonSerializable.fromJsonNode(responseNode, File.class); } /** @@ -629,8 +491,19 @@ CreateFileResponse privateCreate(File file, CreateFileConfig config) { * @return A File object representing the file. */ public File get(String name, GetFileConfig config) { + BuiltRequest builtRequest = buildRequestForGet(name, config); - GetFileParameters.Builder parameterBuilder = GetFileParameters.builder(); + 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(); if (!Common.isZero(name)) { parameterBuilder.name(name); @@ -643,9 +516,11 @@ public File get(String name, GetFileConfig config) { ObjectNode body; String path; if (this.apiClient.vertexAI()) { - throw new UnsupportedOperationException("This method is not supported by the Vertex AI."); + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); } else { - body = getFileParametersToMldev(this.apiClient, parameterNode, null); + body = deleteFileParametersToMldev(parameterNode, null); if (body.get("_url") != null) { path = Common.formatMap("files/{file}", body.get("_url")); } else { @@ -661,32 +536,47 @@ 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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } 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 not supported by the Vertex AI."); - } else { - responseNode = fileFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, File.class); + /** 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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + 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(); } /** @@ -697,11 +587,23 @@ public File get(String name, GetFileConfig config) { * @return The DeleteFileResponse, the response for the delete method. */ public DeleteFileResponse delete(String name, DeleteFileConfig config) { + BuiltRequest builtRequest = buildRequestForDelete(name, config); - DeleteFileParameters.Builder parameterBuilder = DeleteFileParameters.builder(); + try (ApiResponse response = + this.apiClient.request( + "delete", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForDelete(response, config); + } + } - if (!Common.isZero(name)) { - parameterBuilder.name(name); + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateRegisterFiles(List uris, RegisterFilesConfig config) { + + InternalRegisterFilesParameters.Builder parameterBuilder = + InternalRegisterFilesParameters.builder(); + + if (!Common.isZero(uris)) { + parameterBuilder.uris(uris); } if (!Common.isZero(config)) { parameterBuilder.config(config); @@ -711,13 +613,15 @@ public DeleteFileResponse delete(String name, DeleteFileConfig config) { ObjectNode body; String path; if (this.apiClient.vertexAI()) { - throw new UnsupportedOperationException("This method is not supported by the Vertex AI."); + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); } else { - body = deleteFileParametersToMldev(this.apiClient, parameterNode, null); + body = internalRegisterFilesParametersToMldev(parameterNode, null); if (body.get("_url") != null) { - path = Common.formatMap("files/{file}", body.get("_url")); + path = Common.formatMap("files:register", body.get("_url")); } else { - path = "files/{file}"; + path = "files:register"; } } body.remove("_url"); @@ -729,32 +633,153 @@ 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. */ + RegisterFilesResponse processResponseForPrivateRegisterFiles( + ApiResponse response, RegisterFilesConfig 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 != null && config.shouldReturnHttpResponse().orElse(false)) { + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return RegisterFilesResponse.builder() + .sdkHttpResponse(HttpResponse.builder().body(responseString)) + .build(); + } + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); + } + return RegisterFilesResponse.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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + if (!this.apiClient.vertexAI()) { + responseNode = registerFilesResponseFromMldev(responseNode, null); + } + + return JsonSerializable.fromJsonNode(responseNode, RegisterFilesResponse.class); + } + + RegisterFilesResponse privateRegisterFiles(List uris, RegisterFilesConfig config) { + BuiltRequest builtRequest = buildRequestForPrivateRegisterFiles(uris, config); + try (ApiResponse response = this.apiClient.request( - "delete", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateRegisterFiles(response, config); + } + } - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - throw new UnsupportedOperationException("This method is not supported by the Vertex AI."); - } else { - responseNode = deleteFileResponseFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, DeleteFileResponse.class); + /** + * Makes an API request to list the available files. + * + * @param config A {@link ListFilesConfig} for configuring the list request. + * @return A {@link Pager} object that contains the list of files. The pager is an iterable and + * automatically queries the next page once the current page is exhausted. + */ + @SuppressWarnings("PatternMatchingInstanceof") + public Pager list(ListFilesConfig config) { + if (config == null) { + config = ListFilesConfig.builder().build(); } + Function request = + requestConfig -> { + if (!(requestConfig instanceof ListFilesConfig)) { + throw new GenAiIOException( + "Internal error: Pager expected ListFilesConfig but received " + + requestConfig.getClass().getName()); + } + return this.privateList((ListFilesConfig) requestConfig); + }; + return new Pager<>( + Pager.PagedItem.FILES, + request, + (ObjectNode) JsonSerializable.toJsonNode(config), + JsonSerializable.toJsonNode(privateList(config))); + } + + /** + * Registers Google Cloud Storage files for use with the API. + * + * @param credentials The Google Cloud credentials to use for registering the files. + * @param uris The list of GCS URIs to register. + * @param config Optional configuration for the registration request. + * @return The response containing the registered files. + */ + public RegisterFilesResponse registerFiles( + GoogleCredentials credentials, List uris, RegisterFilesConfig config) { + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client."); + } + checkNotNull(credentials, "credentials cannot be null"); + checkNotNull(uris, "uris cannot be null"); + + RegisterFilesConfig updatedConfig = internalPrepareRegisterFilesConfig(credentials, config); + + return privateRegisterFiles(uris, updatedConfig); + } + + /** + * Prepares the configuration for the registerFiles request, including adding authorization + * headers from the provided credentials. + * + * @param credentials The Google Cloud credentials to use. + * @param config Optional configuration to start with. + * @return The updated configuration with authorization headers. + */ + RegisterFilesConfig internalPrepareRegisterFilesConfig( + GoogleCredentials credentials, RegisterFilesConfig config) { + checkNotNull(credentials, "credentials cannot be null"); + + RegisterFilesConfig configToUse = config; + if (configToUse == null) { + configToUse = RegisterFilesConfig.builder().build(); + } + + try { + credentials.refreshIfExpired(); + } catch (IOException | IllegalStateException e) { + throw new GenAiIOException("Failed to refresh credentials.", e); + } + if (credentials.getAccessToken() == null) { + throw new GenAiIOException("Failed to get access token from credentials."); + } + String accessToken = credentials.getAccessToken().getTokenValue(); + + HttpOptions httpOptions = configToUse.httpOptions().orElse(HttpOptions.builder().build()); + Map headers = new HashMap<>(httpOptions.headers().orElse(ImmutableMap.of())); + headers.put("Authorization", "Bearer " + accessToken); + if (credentials.getQuotaProjectId() != null) { + headers.put("x-goog-user-project", credentials.getQuotaProjectId()); + } + + return configToUse.toBuilder() + .httpOptions(httpOptions.toBuilder().headers(headers).build()) + .build(); } /** @@ -767,6 +792,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) { @@ -774,9 +800,10 @@ public File upload(java.io.File file, UploadFileConfig config) { } else { mimeType = Optional.empty(); } - String uploadUrl = createFileInApi(config, mimeType, size); - HttpEntity entity = uploadClient.upload(uploadUrl, inputStream, size); - return fileFromUploadHttpEntity(entity); + String uploadUrl = createFileInApi(config, mimeType, Optional.of(fileName), size); + Optional httpOptions = config != null ? config.httpOptions() : Optional.empty(); + ResponseBody responseBody = uploadClient.upload(uploadUrl, inputStream, size, httpOptions); + return fileFromUploadResponseBody(responseBody); } catch (IOException e) { throw new GenAiIOException("Failed to upload file.", e); } @@ -790,9 +817,11 @@ 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); - HttpEntity entity = uploadClient.upload(uploadUrl, bytes); - return fileFromUploadHttpEntity(entity); + String uploadUrl = + createFileInApi(config, Optional.empty(), Optional.empty(), bytes.length); + Optional httpOptions = config != null ? config.httpOptions() : Optional.empty(); + ResponseBody responseBody = uploadClient.upload(uploadUrl, bytes, httpOptions); + return fileFromUploadResponseBody(responseBody); } /** @@ -804,9 +833,11 @@ 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); - HttpEntity entity = uploadClient.upload(uploadUrl, inputStream, size); - return fileFromUploadHttpEntity(entity); + String uploadUrl = + createFileInApi(config, Optional.empty(), Optional.empty(), size); + Optional httpOptions = config != null ? config.httpOptions() : Optional.empty(); + ResponseBody responseBody = uploadClient.upload(uploadUrl, inputStream, size, httpOptions); + return fileFromUploadResponseBody(responseBody); } /** @@ -821,23 +852,25 @@ public File upload(String filePath, UploadFileConfig config) { return upload(file, config); } - private File fileFromUploadHttpEntity(HttpEntity entity) { + private File fileFromUploadResponseBody(ResponseBody responseBody) { String responseString; try { - responseString = EntityUtils.toString(entity); + responseString = responseBody.string(); } catch (IOException e) { throw new GenAiIOException("Failed to read HTTP response.", e); } JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); responseNode = responseNode.get("file"); - responseNode = fileFromMldev(this.apiClient, 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(); + Optional userHttpOptions = Optional.empty(); if (config != null) { + userHttpOptions = config.httpOptions(); if (config.name().isPresent()) { apiFileBuilder.name(config.name().get()); } @@ -854,26 +887,13 @@ private String createFileInApi(UploadFileConfig config, Optional mimeTyp if (apiFile.name().isPresent() && !apiFile.name().get().startsWith("files/")) { apiFile = apiFile.toBuilder().name("files/" + apiFile.name().get()).build(); } - - String actualMimeType = - mimeType.orElse( - apiFile - .mimeType() - .orElseThrow( - () -> - new IllegalArgumentException( - "Unknown mime type: Could not determine mime type for your file, please" - + " set the mimeType config argument"))); - - Map createFileHeaders = new HashMap<>(); - createFileHeaders.put("Content-Type", "application/json"); - createFileHeaders.put("X-Goog-Upload-Protocol", "resumable"); - 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); - + Optional mimeTypeToUse = + mimeType.isPresent() + ? mimeType + : apiFile.mimeType().isPresent() ? apiFile.mimeType() : Optional.empty(); HttpOptions createFileHttpOptions = - HttpOptions.builder().apiVersion("").headers(createFileHeaders).build(); + UploadClient.buildResumableUploadHttpOptions( + userHttpOptions, mimeTypeToUse, fileName, size); CreateFileResponse createFileResponse = privateCreate( @@ -883,19 +903,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.")); } /** @@ -908,7 +929,7 @@ private String createFileInApi(UploadFileConfig config, Optional mimeTyp public void download(String fileName, String downloadPath, DownloadFileConfig config) { checkNotNull(fileName); checkNotNull(downloadPath); - String extractedFileName = Transformers.tFileName(apiClient, fileName); + String extractedFileName = Transformers.tFileName(fileName); downloadTo(extractedFileName, downloadPath, config); } @@ -922,7 +943,7 @@ public void download(String fileName, String downloadPath, DownloadFileConfig co public void download(Video video, String downloadPath, DownloadFileConfig config) { checkNotNull(video); checkNotNull(downloadPath); - String extractedFileName = Transformers.tFileName(apiClient, video); + String extractedFileName = Transformers.tFileName(video); if (extractedFileName != null) { downloadTo(extractedFileName, downloadPath, config); } else { @@ -944,7 +965,7 @@ public void download(Video video, String downloadPath, DownloadFileConfig config public void download(File file, String downloadPath, DownloadFileConfig config) { checkNotNull(file); checkNotNull(downloadPath); - String extractedFileName = Transformers.tFileName(apiClient, file); + String extractedFileName = Transformers.tFileName(file); downloadTo(extractedFileName, downloadPath, config); } @@ -959,7 +980,7 @@ public void download( GeneratedVideo generatedVideo, String downloadPath, DownloadFileConfig config) { checkNotNull(generatedVideo); checkNotNull(downloadPath); - String extractedFileName = Transformers.tFileName(apiClient, generatedVideo); + String extractedFileName = Transformers.tFileName(generatedVideo); if (extractedFileName != null) { downloadTo(extractedFileName, downloadPath, config); } else { @@ -982,8 +1003,7 @@ private void downloadTo(String fileName, String downloadPath, DownloadFileConfig this.apiClient.request( "get", String.format("files/%s:download?alt=media", fileName), "", httpOptions); try (FileOutputStream outputStream = new FileOutputStream(downloadPath)) { - HttpEntity entity = response.getEntity(); - entity.writeTo(outputStream); + outputStream.write(response.getBody().bytes()); } catch (IOException e) { throw new GenAiIOException("Failed to download file.", e); } @@ -996,29 +1016,4 @@ private void saveTo(byte[] bytes, String downloadPath) { throw new GenAiIOException("Failed to save file.", e); } } - - /** - * makes an API request to list the available files. - * - * @param config A {@link ListFilesConfig} for configuring the list request. - * @return A {@link Pager} object that contains the list of files. The pager is an iterable and - * automatically queries the next page once the current page is exhausted. - */ - @SuppressWarnings("PatternMatchingInstanceof") - public Pager list(ListFilesConfig config) { - Function request = - requestConfig -> { - if (!(requestConfig instanceof ListFilesConfig)) { - throw new GenAiIOException( - "Internal error: Pager expected ListFilesConfig but received " - + requestConfig.getClass().getName()); - } - return this.privateList((ListFilesConfig) requestConfig); - }; - return new Pager<>( - Pager.PagedItem.FILES, - request, - (ObjectNode) JsonSerializable.toJsonNode(config), - JsonSerializable.toJsonNode(privateList(config))); - } } diff --git a/src/main/java/com/google/genai/HttpApiClient.java b/src/main/java/com/google/genai/HttpApiClient.java index d7375d20704..fcc8a887f11 100644 --- a/src/main/java/com/google/genai/HttpApiClient.java +++ b/src/main/java/com/google/genai/HttpApiClient.java @@ -18,154 +18,140 @@ import com.google.api.core.InternalApi; import com.google.auth.oauth2.GoogleCredentials; -import com.google.common.collect.ImmutableMap; import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.ClientOptions; import com.google.genai.types.HttpOptions; import java.io.IOException; -import java.util.Map; +import java.time.Duration; import java.util.Optional; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; /** Base client for the HTTP APIs. This is for internal use only. */ @InternalApi public class HttpApiClient extends ApiClient { /** Constructs an ApiClient for Google AI APIs. */ - HttpApiClient(Optional apiKey, Optional httpOptions) { - super(apiKey, httpOptions); + public HttpApiClient( + Optional apiKey, + Optional httpOptions, + Optional clientOptions) { + super(apiKey, httpOptions, clientOptions); } /** Constructs an ApiClient for Vertex AI APIs. */ - HttpApiClient( + public HttpApiClient( + Optional apiKey, Optional project, Optional location, Optional credentials, - Optional httpOptions) { - super(project, location, credentials, httpOptions); + Optional httpOptions, + Optional clientOptions) { + super(apiKey, project, location, credentials, httpOptions, clientOptions); } - /** Sends a Http request given the http method, path, request json string, and http options. */ + /** + * Sends a Http request given the http method, path, request json string, and http options. + * Request bodies included for non-POST/PUT/PATCH methods will be ignored. + */ @Override public HttpApiResponse request( String httpMethod, String path, String requestJson, Optional requestHttpOptions) { - boolean queryBaseModel = - httpMethod.equalsIgnoreCase("GET") && path.startsWith("publishers/google/models"); - if (this.vertexAI() && !path.startsWith("projects/") && !queryBaseModel) { - path = - String.format("projects/%s/locations/%s/", this.project.get(), this.location.get()) - + path; - } - - HttpOptions mergedHttpOptions = mergeHttpOptions(requestHttpOptions.orElse(null)); + return executeRequest(buildRequest(httpMethod, path, requestJson, requestHttpOptions)); + } - String requestUrl; + /** Sends a Http request given the http method, path, request bytes, and http options. */ + @Override + public HttpApiResponse request( + String httpMethod, + String url, + byte[] requestBytes, + Optional requestHttpOptions) { + return executeRequest(buildRequest(httpMethod, url, requestBytes, requestHttpOptions)); + } - if (mergedHttpOptions.apiVersion().get().isEmpty()) { - requestUrl = String.format("%s/%s", mergedHttpOptions.baseUrl().get(), path); - } else { - requestUrl = - String.format( - "%s/%s/%s", - mergedHttpOptions.baseUrl().get(), mergedHttpOptions.apiVersion().get(), path); + /** Executes the given HTTP request. */ + private HttpApiResponse executeRequest(Request request) { + try { + OkHttpClient client = httpClient; + HttpOptions requestOptions = request.tag(HttpOptions.class); + if (requestOptions != null && requestOptions.timeout().isPresent()) { + client = + httpClient + .newBuilder() + .callTimeout(Duration.ofMillis(requestOptions.timeout().get())) + .build(); + } + return new HttpApiResponse(client.newCall(request).execute()); + } catch (IOException e) { + throw new GenAiIOException("Failed to execute HTTP request.", e); } + } - if (httpMethod.equalsIgnoreCase("POST")) { - HttpPost httpPost = new HttpPost(requestUrl); - setHeaders(httpPost, mergedHttpOptions); - httpPost.setEntity(new StringEntity(requestJson, ContentType.APPLICATION_JSON)); - return executeRequest(httpPost); - } else if (httpMethod.equalsIgnoreCase("GET")) { - HttpGet httpGet = new HttpGet(requestUrl); - setHeaders(httpGet, mergedHttpOptions); - return executeRequest(httpGet); - } else if (httpMethod.equalsIgnoreCase("DELETE")) { - HttpDelete httpDelete = new HttpDelete(requestUrl); - setHeaders(httpDelete, mergedHttpOptions); - return executeRequest(httpDelete); - } else if (httpMethod.equalsIgnoreCase("PATCH")) { - HttpPatch httpPatch = new HttpPatch(requestUrl); - setHeaders(httpPatch, mergedHttpOptions); - httpPatch.setEntity(new StringEntity(requestJson, ContentType.APPLICATION_JSON)); - return executeRequest(httpPatch); - } else { - throw new IllegalArgumentException("Unsupported HTTP method: " + httpMethod); - } + /** + * 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 ApiResponse request( + public CompletableFuture asyncRequest( String httpMethod, String url, byte[] requestBytes, Optional requestHttpOptions) { - HttpOptions mergedHttpOptions = mergeHttpOptions(requestHttpOptions.orElse(null)); - if (httpMethod.equalsIgnoreCase("POST")) { - HttpPost httpPost = new HttpPost(url); - setHeaders(httpPost, mergedHttpOptions); - httpPost.setEntity(new ByteArrayEntity(requestBytes)); - return executeRequest(httpPost); - } else { - throw new IllegalArgumentException( - "The request method with bytes is only supported for POST. Unsupported HTTP method: " - + httpMethod); - } + return asyncExecuteRequest(buildRequest(httpMethod, url, requestBytes, requestHttpOptions)); } - /** Sets the required headers (including auth) on the request object. */ - private void setHeaders(HttpRequestBase request, HttpOptions requestHttpOptions) { - for (Map.Entry header : - requestHttpOptions.headers().orElse(ImmutableMap.of()).entrySet()) { - request.setHeader(header.getKey(), header.getValue()); + /** Executes the given HTTP request asynchronously, this method is non-blocking. */ + private CompletableFuture asyncExecuteRequest(Request request) { + CompletableFuture future = new CompletableFuture<>(); + + OkHttpClient client = httpClient; + HttpOptions requestOptions = request.tag(HttpOptions.class); + if (requestOptions != null && requestOptions.timeout().isPresent()) { + client = + httpClient + .newBuilder() + .callTimeout(Duration.ofMillis(requestOptions.timeout().get())) + .build(); } - if (apiKey.isPresent()) { - request.setHeader("x-goog-api-key", apiKey.get()); - } else { - GoogleCredentials cred = - credentials.orElseThrow(() -> new IllegalStateException("credentials is required")); - try { - cred.refreshIfExpired(); - } catch (IOException e) { - throw new GenAiIOException("Failed to refresh credentials.", e); - } - String accessToken; - try { - accessToken = cred.getAccessToken().getTokenValue(); - } catch (NullPointerException e) { - // For test cases where the access token is not available. - if (e.getMessage() - .contains( - "because the return value of" - + " \"com.google.auth.oauth2.GoogleCredentials.getAccessToken()\" is null")) { - accessToken = ""; - } else { - throw e; - } - } - request.setHeader("Authorization", "Bearer " + accessToken); + client + .newCall(request) + .enqueue( + new Callback() { - if (cred.getQuotaProjectId() != null) { - request.setHeader("x-goog-user-project", cred.getQuotaProjectId()); - } - } - } + @Override + public void onFailure(Call call, IOException e) { + future.completeExceptionally( + new GenAiIOException("Failed to execute HTTP request.", e)); + } - /** Executes the given HTTP request. */ - private HttpApiResponse executeRequest(HttpRequestBase request) { - try { - return new HttpApiResponse(httpClient.execute(request)); - } catch (IOException e) { - throw 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/HttpApiResponse.java b/src/main/java/com/google/genai/HttpApiResponse.java index 1e7f6fc4250..14938905f09 100644 --- a/src/main/java/com/google/genai/HttpApiResponse.java +++ b/src/main/java/com/google/genai/HttpApiResponse.java @@ -17,42 +17,36 @@ package com.google.genai; import com.google.genai.errors.ApiException; -import com.google.genai.errors.GenAiIOException; -import java.io.IOException; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.client.methods.CloseableHttpResponse; +import okhttp3.Headers; +import okhttp3.Response; +import okhttp3.ResponseBody; /** Wraps a real HTTP response to expose the methods needed by the GenAI SDK. */ final class HttpApiResponse extends ApiResponse { - private final CloseableHttpResponse response; + private final Response response; /** Constructs a HttpApiResponse instance with the response. */ - public HttpApiResponse(CloseableHttpResponse response) { + public HttpApiResponse(Response response) { this.response = response; } - /** Returns the HttpEntity from the response. */ + /** Returns the ResponseBody from the response. */ @Override - public HttpEntity getEntity() { + public ResponseBody getBody() { ApiException.throwFromResponse(response); - return response.getEntity(); + return response.body(); } /** Returns all of the headers from the response. */ @Override - public Header[] getHeaders() { - return response.getAllHeaders(); + public Headers getHeaders() { + return response.headers(); } /** Closes the Http response. */ @Override public void close() { - try { - response.close(); - } catch (IOException e) { - throw new GenAiIOException("Failed to close the HTTP response.", e); - } + response.close(); } } diff --git a/src/main/java/com/google/genai/JsonSerializable.java b/src/main/java/com/google/genai/JsonSerializable.java index 57874b9600e..52d1db05f4e 100644 --- a/src/main/java/com/google/genai/JsonSerializable.java +++ b/src/main/java/com/google/genai/JsonSerializable.java @@ -18,8 +18,10 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.StreamReadConstraints; +import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; @@ -27,18 +29,25 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - import com.google.api.core.InternalApi; import com.google.genai.errors.GenAiIOException; +import java.util.logging.Logger; /** 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(); + private static final Logger logger = Logger.getLogger(JsonSerializable.class.getName()); + + /** + * System property to override the default max JSON string length (20MB) in read constraints. + * E.g., if you want to change the limit to 100MB, you can set it via + * `-Dgenai.json.maxReadLength=100000000`. + */ + public static final String MAX_READ_LENGTH_PROPERTY = "genai.json.maxReadLength"; /** Custom Jackson serializer for {@link java.time.Duration} to output "Xs" format. */ static class CustomDurationSerializer extends JsonSerializer { @@ -59,7 +68,8 @@ public void serialize( /** Custom Jackson deserializer for {@link java.time.Duration} to parse "Xs" format. */ static class CustomDurationDeserializer extends JsonDeserializer { @Override - public java.time.Duration deserialize(JsonParser p, DeserializationContext ctxt) throws java.io.IOException, JsonProcessingException { + public java.time.Duration deserialize(JsonParser p, DeserializationContext ctxt) + throws java.io.IOException, JsonProcessingException { String value = p.getValueAsString(); if (value == null || value.isEmpty()) { @@ -71,19 +81,33 @@ 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); } } } + /** Configures the stream read constraints for the JSON parser. */ + private static void configureStreamReadConstraints(int maxReadLength) { + if (maxReadLength <= 0) { + throw new IllegalArgumentException("Invalid JSON max read length: " + maxReadLength); + } + logger.info("Overriding default JSON max string length. New value = " + maxReadLength); + StreamReadConstraints constraints = + StreamReadConstraints.builder().maxStringLength(maxReadLength).build(); + objectMapper.getFactory().setStreamReadConstraints(constraints); + } + 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); @@ -99,6 +123,18 @@ public java.time.Duration deserialize(JsonParser p, DeserializationContext ctxt) objectMapper.registerModule(new JavaTimeModule()); objectMapper.registerModule(customModule); + try { + String propertyValue = System.getProperty(MAX_READ_LENGTH_PROPERTY); + if (propertyValue != null && !propertyValue.isEmpty()) { + int maxStringLength = Integer.parseInt(propertyValue); + configureStreamReadConstraints(maxStringLength); + } + } catch (NumberFormatException e) { + logger.warning( + "Failed to parse system property [" + + MAX_READ_LENGTH_PROPERTY + + "]. Using default 20MB limit."); + } } /** Serializes the instance to a Json string. */ @@ -107,7 +143,7 @@ public String toJson() { } /** Serializes an object to a Json string. */ - static String toJsonString(Object object) { + public static String toJsonString(Object object) { try { return objectMapper.writeValueAsString(object); } catch (JsonProcessingException e) { @@ -116,14 +152,13 @@ static String toJsonString(Object object) { } /** Serializes an object to a JsonNode. */ - static JsonNode toJsonNode(Object object) { + public static JsonNode toJsonNode(Object object) { return objectMapper.valueToTree(object); } /** Deserializes a Json string to an object of the given type. This is for internal use only. */ @InternalApi - protected static T fromJsonString( - String jsonString, Class clazz) { + public static T fromJsonString(String jsonString, Class clazz) { try { return objectMapper.readValue(jsonString, clazz); } catch (JsonProcessingException e) { @@ -132,7 +167,8 @@ protected static T fromJsonString( } /** Deserializes a JsonNode to an object of the given type. */ - static T fromJsonNode(JsonNode jsonNode, Class clazz) { + @InternalApi + public static T fromJsonNode(JsonNode jsonNode, Class clazz) { try { return objectMapper.treeToValue(jsonNode, clazz); } catch (JsonProcessingException e) { @@ -141,11 +177,27 @@ 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) { throw new GenAiIOException("Failed to parse the JSON string.", e); } } + + /** + * Overrides the default maximum JSON string length (20MB) for the JSON parser. + * + *

    Warning: This modifies a global static setting. It will overrides the system property + * setting via {@link #MAX_READ_LENGTH_PROPERTY}. This method is not thread-safe. + * + * @param maxReadLength the new maximum string length in bytes (e.g., 100_000_000 for 100MB). + */ + public static void setMaxReadLength(int maxReadLength) { + configureStreamReadConstraints(maxReadLength); + } + + public static ObjectMapper objectMapper() { + return objectMapper; + } } diff --git a/src/main/java/com/google/genai/LiveConverters.java b/src/main/java/com/google/genai/LiveConverters.java index f28cdc12689..2e478a20cf3 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,1569 +32,1025 @@ public LiveConverters(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode prebuiltVoiceConfigToMldev( - ApiClient apiClient, 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"})); + ObjectNode audioTranscriptionConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"languageCodes"}))) { + throw new IllegalArgumentException( + "languageCodes parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode prebuiltVoiceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceName"}) != null) { + ObjectNode authConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"apiKey"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceName"}, - Common.getValueByPath(fromObject, new String[] {"voiceName"})); + new String[] {"apiKey"}, + Common.getValueByPath(fromObject, new String[] {"apiKey"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}))) { + throw new IllegalArgumentException( + "apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode voiceConfigToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"prebuiltVoiceConfig"}, - prebuiltVoiceConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"authType"}))) { + throw new IllegalArgumentException( + "authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - return toObject; - } + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"}))) { + throw new IllegalArgumentException( + "googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent" + + " Platform mode, not in Gemini Developer API mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode voiceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"prebuiltVoiceConfig"}, - prebuiltVoiceConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}))) { + throw new IllegalArgumentException( + "httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"oauthConfig"}))) { + throw new IllegalArgumentException( + "oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"oidcConfig"}))) { + throw new IllegalArgumentException( + "oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode speakerVoiceConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"speaker"}) != null) { + ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { Common.setValueByPath( toObject, - new String[] {"speaker"}, - Common.getValueByPath(fromObject, new String[] {"speaker"})); + new String[] {"data"}, + Common.getValueByPath(fromObject, new String[] {"data"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException( + "displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode speakerVoiceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"speaker"}))) { - throw new IllegalArgumentException("speaker parameter is not supported in Vertex AI."); + 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.isZero(Common.getValueByPath(fromObject, new String[] {"voiceConfig"}))) { - throw new IllegalArgumentException("voiceConfig parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"role"}, + Common.getValueByPath(fromObject, new String[] {"role"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode multiSpeakerVoiceConfigToMldev( - 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"}); + 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( - speakerVoiceConfigToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(partToVertex(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"speakerVoiceConfigs"}, result); + Common.setValueByPath(toObject, new String[] {"parts"}, result); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode multiSpeakerVoiceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"speakerVoiceConfigs"}))) { - throw new IllegalArgumentException( - "speakerVoiceConfigs parameter is not supported in Vertex AI."); + 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( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + 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 only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"multiSpeakerVoiceConfig"}, - multiSpeakerVoiceConfigToMldev( - apiClient, - 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 speechConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { + ObjectNode functionCallToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"id"}) != null) { Common.setValueByPath( - toObject, - new String[] {"voiceConfig"}, - voiceConfigToVertex( - apiClient, - 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."); + toObject, new String[] {"id"}, Common.getValueByPath(fromObject, new String[] {"id"})); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"args"}) != null) { Common.setValueByPath( toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + new String[] {"args"}, + Common.getValueByPath(fromObject, new String[] {"args"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + toObject, + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"partialArgs"}))) { + throw new IllegalArgumentException( + "partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"willContinue"}))) { + throw new IllegalArgumentException( + "willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { + ObjectNode generationConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}) != null) { Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + toObject, + new String[] {"modelConfig"}, + Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"responseJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"audioTimestamp"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode blobToMldev(ApiClient apiClient, 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."); + new String[] {"audioTimestamp"}, + Common.getValueByPath(fromObject, new String[] {"audioTimestamp"})); } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"candidateCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + new String[] {"candidateCount"}, + Common.getValueByPath(fromObject, new String[] {"candidateCount"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"enableAffectiveDialog"}, + Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode blobToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"frequencyPenalty"}, + Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"})); } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"logprobs"}) != null) { Common.setValueByPath( toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + new String[] {"logprobs"}, + Common.getValueByPath(fromObject, new String[] {"logprobs"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToMldev(ApiClient apiClient, 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."); + new String[] {"maxOutputTokens"}, + Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"presencePenalty"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"presencePenalty"}, + Common.getValueByPath(fromObject, new String[] {"presencePenalty"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseLogprobs"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"responseLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseMimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + new String[] {"responseMimeType"}, + Common.getValueByPath(fromObject, new String[] {"responseMimeType"})); } - 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"})); + new String[] {"responseModalities"}, + Common.getValueByPath(fromObject, new String[] {"responseModalities"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode partToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseSchema"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + new String[] {"responseSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseSchema"})); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"routingConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + new String[] {"routingConfig"}, + Common.getValueByPath(fromObject, new String[] {"routingConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( toObject, - new String[] {"inlineData"}, - blobToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + new String[] {"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"}, - fileDataToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + new String[] {"speechConfig"}, + Common.getValueByPath(fromObject, new String[] {"speechConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"stopSequences"}) != null) { Common.setValueByPath( toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + new String[] {"stopSequences"}, + Common.getValueByPath(fromObject, new String[] {"stopSequences"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + new String[] {"temperature"}, + Common.getValueByPath(fromObject, new String[] {"temperature"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + new String[] {"thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + new String[] {"topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + new String[] {"topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); } - 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[] {"enableEnhancedCivicAnswers"}))) { + throw new IllegalArgumentException( + "enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not" + + " in Gemini Enterprise Agent Platform mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode partToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + ObjectNode googleMapsToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"authConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataToVertex( - apiClient, + new String[] {"authConfig"}, + authConfigToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), + Common.getValueByPath(fromObject, new String[] {"authConfig"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableWidget"}) != null) { Common.setValueByPath( toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + new String[] {"enableWidget"}, + Common.getValueByPath(fromObject, new String[] {"enableWidget"})); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"searchTypes"}) != null) { Common.setValueByPath( toObject, - new String[] {"inlineData"}, - blobToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + new String[] {"searchTypes"}, + Common.getValueByPath(fromObject, new String[] {"searchTypes"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"blockingConfidence"}))) { + throw new IllegalArgumentException( + "blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); } - 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.isZero(Common.getValueByPath(fromObject, new String[] {"excludeDomains"}))) { + throw new IllegalArgumentException( + "excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { Common.setValueByPath( toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + new String[] {"timeRangeFilter"}, + Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentToMldev(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"}); + ObjectNode liveClientContentToMldev(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(partToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(contentToMldev(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"parts"}, result); + Common.setValueByPath(toObject, new String[] {"turns"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"turnComplete"}) != null) { Common.setValueByPath( toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + new String[] {"turnComplete"}, + Common.getValueByPath(fromObject, new String[] {"turnComplete"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentToVertex(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"}); + 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(partToVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(contentToVertex(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"parts"}, result); + Common.setValueByPath(toObject, new String[] {"turns"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"turnComplete"}) != null) { Common.setValueByPath( toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + new String[] {"turnComplete"}, + Common.getValueByPath(fromObject, new String[] {"turnComplete"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"behavior"}) != null) { + ObjectNode liveClientMessageToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"setup"}) != null) { Common.setValueByPath( toObject, - new String[] {"behavior"}, - Common.getValueByPath(fromObject, new String[] {"behavior"})); + new String[] {"setup"}, + liveClientSetupToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"setup"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"clientContent"}) != null) { Common.setValueByPath( toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + new String[] {"clientContent"}, + liveClientContentToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"clientContent"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInput"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"realtimeInput"}, + liveClientRealtimeInputToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"realtimeInput"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"}) != null) { Common.setValueByPath( toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); + new String[] {"realtime_input"}, + liveSendRealtimeInputParametersToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); + new String[] {"toolResponse"}, + Common.getValueByPath(fromObject, new String[] {"toolResponse"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToVertex( - 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."); + 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[] {"description"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"clientContent"}) != null) { Common.setValueByPath( toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + new String[] {"clientContent"}, + liveClientContentToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"clientContent"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInput"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"realtimeInput"}, + liveClientRealtimeInputToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"realtimeInput"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"}) != null) { Common.setValueByPath( toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); + new String[] {"realtime_input"}, + liveSendRealtimeInputParametersToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); + new String[] {"toolResponse"}, + Common.getValueByPath(fromObject, new String[] {"toolResponse"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToMldev(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"})); - } + ObjectNode liveClientRealtimeInputToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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(); - if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); + for (JsonNode item : keyArray) { + result.add(blobToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"mediaChunks"}, result); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToVertex(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[] {"audio"}) != null) { Common.setValueByPath( toObject, - new String[] {"startTime"}, - Common.getValueByPath(fromObject, new String[] {"startTime"})); + new String[] {"audio"}, + blobToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"audio"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}) != null) { Common.setValueByPath( toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); + new String[] {"audioStreamEnd"}, + Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToMldev( - 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[] {"video"}) != null) { Common.setValueByPath( toObject, - new String[] {"timeRangeFilter"}, - intervalToMldev( - apiClient, + new String[] {"video"}, + blobToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), + Common.getValueByPath(fromObject, new String[] {"video"})), toObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToVertex( - 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[] {"text"}) != null) { Common.setValueByPath( toObject, - new String[] {"timeRangeFilter"}, - intervalToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToMldev( - 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[] {"activityStart"}) != null) { Common.setValueByPath( toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + new String[] {"activityStart"}, + Common.getValueByPath(fromObject, new String[] {"activityStart"})); } - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); + new String[] {"activityEnd"}, + Common.getValueByPath(fromObject, new String[] {"activityEnd"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + ObjectNode liveClientRealtimeInputToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"mediaChunks"}) != null) { Common.setValueByPath( toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + new String[] {"mediaChunks"}, + Common.getValueByPath(fromObject, new String[] {"mediaChunks"})); } - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); + new String[] {"audio"}, + Common.getValueByPath(fromObject, new String[] {"audio"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}))) { + throw new IllegalArgumentException( + "audioStreamEnd parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), - toObject)); + new String[] {"video"}, + Common.getValueByPath(fromObject, new String[] {"video"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), - toObject)); + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode enterpriseWebSearchToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode enterpriseWebSearchToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode apiKeyConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyString"}))) { - throw new IllegalArgumentException("apiKeyString parameter is not supported in Gemini API."); + if (Common.getValueByPath(fromObject, new String[] {"activityStart"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"activityStart"}, + Common.getValueByPath(fromObject, new String[] {"activityStart"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode apiKeyConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyString"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { Common.setValueByPath( toObject, - new String[] {"apiKeyString"}, - Common.getValueByPath(fromObject, new String[] {"apiKeyString"})); + new String[] {"activityEnd"}, + Common.getValueByPath(fromObject, new String[] {"activityEnd"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode authConfigToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}))) { - throw new IllegalArgumentException("apiKeyConfig parameter is not supported in Gemini API."); - } - - 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) { + ObjectNode liveClientSetupToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleServiceAccountConfig"}, - Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"})); + new String[] {"model"}, + Common.getValueByPath(fromObject, new String[] {"model"})); } - if (Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"generationConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"httpBasicAuthConfig"}, - Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"})); + new String[] {"generationConfig"}, + Common.getValueByPath(fromObject, new String[] {"generationConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"oauthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( toObject, - new String[] {"oauthConfig"}, - Common.getValueByPath(fromObject, new String[] {"oauthConfig"})); + new String[] {"systemInstruction"}, + contentToMldev( + JsonSerializable.toJsonNode( + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"oidcConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"oidcConfig"}, - Common.getValueByPath(fromObject, new String[] {"oidcConfig"})); - } + 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(); - return toObject; - } + for (JsonNode item : keyArray) { + result.add(toolToMldev(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); + } + Common.setValueByPath(toObject, new String[] {"tools"}, result); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode authConfigToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"apiKeyConfig"}, - apiKeyConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"})), - toObject)); + new String[] {"realtimeInputConfig"}, + Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"authType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sessionResumption"}) != null) { Common.setValueByPath( toObject, - new String[] {"authType"}, - Common.getValueByPath(fromObject, new String[] {"authType"})); + new String[] {"sessionResumption"}, + sessionResumptionConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"sessionResumption"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleServiceAccountConfig"}, - Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"})); + new String[] {"contextWindowCompression"}, + Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})); } - if (Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { Common.setValueByPath( toObject, - new String[] {"httpBasicAuthConfig"}, - Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"})); + new String[] {"inputAudioTranscription"}, + audioTranscriptionConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"oauthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"}) != null) { Common.setValueByPath( toObject, - new String[] {"oauthConfig"}, - Common.getValueByPath(fromObject, new String[] {"oauthConfig"})); + new String[] {"outputAudioTranscription"}, + audioTranscriptionConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"oidcConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { Common.setValueByPath( toObject, - new String[] {"oidcConfig"}, - Common.getValueByPath(fromObject, new String[] {"oidcConfig"})); + new String[] {"proactivity"}, + Common.getValueByPath(fromObject, new String[] {"proactivity"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleMapsToMldev(ApiClient apiClient, 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.isZero(Common.getValueByPath(fromObject, new String[] {"explicitVadSignal"}))) { + throw new IllegalArgumentException( + "explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleMapsToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"authConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"avatarConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"authConfig"}, - authConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"authConfig"})), - toObject)); + new String[] {"avatarConfig"}, + Common.getValueByPath(fromObject, new String[] {"avatarConfig"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetySettings"}) != null) { ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"safetySettings"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add( - functionDeclarationToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(safetySettingToMldev(JsonSerializable.toJsonNode(item), toObject)); } - Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); + Common.setValueByPath(toObject, new String[] {"safetySettings"}, result); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { - throw new IllegalArgumentException("retrieval parameter is not supported in Gemini API."); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + @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[] {"googleSearch"}, - googleSearchToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); + new String[] {"model"}, + Common.getValueByPath(fromObject, new String[] {"model"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"generationConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToMldev( - apiClient, + new String[] {"generationConfig"}, + generationConfigToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), + Common.getValueByPath(fromObject, new String[] {"generationConfig"})), 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[] {"systemInstruction"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlContext"}, - urlContextToMldev( - apiClient, + new String[] {"systemInstruction"}, + contentToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); + (ArrayNode) + Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add( - functionDeclarationToVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(toolToVertex(JsonSerializable.toJsonNode(Transformers.tTool(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"})); + Common.setValueByPath(toObject, new String[] {"tools"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleSearch"}, - googleSearchToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); + new String[] {"realtimeInputConfig"}, + Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sessionResumption"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - toObject)); + new String[] {"sessionResumption"}, + Common.getValueByPath(fromObject, new String[] {"sessionResumption"})); } - if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { Common.setValueByPath( toObject, - new String[] {"enterpriseWebSearch"}, - enterpriseWebSearchToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})), - toObject)); + new String[] {"contextWindowCompression"}, + Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleMaps"}, - googleMapsToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleMaps"})), - toObject)); + new String[] {"inputAudioTranscription"}, + Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})); } - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlContext"}, - urlContextToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), - toObject)); + new String[] {"outputAudioTranscription"}, + Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + new String[] {"proactivity"}, + Common.getValueByPath(fromObject, new String[] {"proactivity"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode sessionResumptionConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"handle"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"explicitVadSignal"}) != null) { Common.setValueByPath( toObject, - new String[] {"handle"}, - Common.getValueByPath(fromObject, new String[] {"handle"})); + new String[] {"explicitVadSignal"}, + Common.getValueByPath(fromObject, new String[] {"explicitVadSignal"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"transparent"}))) { - throw new IllegalArgumentException("transparent parameter is not supported in Gemini API."); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode sessionResumptionConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"handle"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"avatarConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"handle"}, - Common.getValueByPath(fromObject, new String[] {"handle"})); + new String[] {"avatarConfig"}, + Common.getValueByPath(fromObject, new String[] {"avatarConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"transparent"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetySettings"}) != null) { Common.setValueByPath( toObject, - new String[] {"transparent"}, - Common.getValueByPath(fromObject, new String[] {"transparent"})); + new String[] {"safetySettings"}, + Common.getValueByPath(fromObject, new String[] {"safetySettings"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode audioTranscriptionConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode audioTranscriptionConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } + ObjectNode liveConnectConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); - @ExcludeFromGeneratedCoverageReport - ObjectNode automaticActivityDetectionToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"disabled"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { Common.setValueByPath( - toObject, - new String[] {"disabled"}, - Common.getValueByPath(fromObject, new String[] {"disabled"})); + parentObject, + new String[] {"setup", "generationConfig", "responseModalities"}, + Common.getValueByPath(fromObject, new String[] {"responseModalities"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOfSpeechSensitivity"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { Common.setValueByPath( - toObject, - new String[] {"startOfSpeechSensitivity"}, - Common.getValueByPath(fromObject, new String[] {"startOfSpeechSensitivity"})); + parentObject, + new String[] {"setup", "generationConfig", "temperature"}, + Common.getValueByPath(fromObject, new String[] {"temperature"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOfSpeechSensitivity"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { Common.setValueByPath( - toObject, - new String[] {"endOfSpeechSensitivity"}, - Common.getValueByPath(fromObject, new String[] {"endOfSpeechSensitivity"})); + parentObject, + new String[] {"setup", "generationConfig", "topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); } - if (Common.getValueByPath(fromObject, new String[] {"prefixPaddingMs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { Common.setValueByPath( - toObject, - new String[] {"prefixPaddingMs"}, - Common.getValueByPath(fromObject, new String[] {"prefixPaddingMs"})); + parentObject, + new String[] {"setup", "generationConfig", "topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); } - if (Common.getValueByPath(fromObject, new String[] {"silenceDurationMs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { Common.setValueByPath( - toObject, - new String[] {"silenceDurationMs"}, - Common.getValueByPath(fromObject, new String[] {"silenceDurationMs"})); + parentObject, + new String[] {"setup", "generationConfig", "maxOutputTokens"}, + Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode automaticActivityDetectionToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"disabled"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( - toObject, - new String[] {"disabled"}, - Common.getValueByPath(fromObject, new String[] {"disabled"})); + parentObject, + new String[] {"setup", "generationConfig", "mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOfSpeechSensitivity"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( - toObject, - new String[] {"startOfSpeechSensitivity"}, - Common.getValueByPath(fromObject, new String[] {"startOfSpeechSensitivity"})); + parentObject, + new String[] {"setup", "generationConfig", "seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOfSpeechSensitivity"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"endOfSpeechSensitivity"}, - Common.getValueByPath(fromObject, new String[] {"endOfSpeechSensitivity"})); + parentObject, + new String[] {"setup", "generationConfig", "speechConfig"}, + Transformers.tLiveSpeechConfig( + Common.getValueByPath(fromObject, new String[] {"speechConfig"}))); } - if (Common.getValueByPath(fromObject, new String[] {"prefixPaddingMs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"prefixPaddingMs"}, - Common.getValueByPath(fromObject, new String[] {"prefixPaddingMs"})); + parentObject, + new String[] {"setup", "generationConfig", "thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"silenceDurationMs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { Common.setValueByPath( - toObject, - new String[] {"silenceDurationMs"}, - Common.getValueByPath(fromObject, new String[] {"silenceDurationMs"})); + parentObject, + new String[] {"setup", "generationConfig", "enableAffectiveDialog"}, + Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode realtimeInputConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"automaticActivityDetection"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { Common.setValueByPath( - toObject, - new String[] {"automaticActivityDetection"}, - automaticActivityDetectionToMldev( - apiClient, + parentObject, + new String[] {"setup", "systemInstruction"}, + contentToMldev( 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 realtimeInputConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"automaticActivityDetection"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"automaticActivityDetection"}, - automaticActivityDetectionToVertex( - apiClient, - 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 slidingWindowToMldev( - ApiClient apiClient, 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 slidingWindowToVertex( - ApiClient apiClient, 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 contextWindowCompressionConfigToMldev( - ApiClient apiClient, 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"}, - slidingWindowToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"slidingWindow"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contextWindowCompressionConfigToVertex( - ApiClient apiClient, 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( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"slidingWindow"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode proactivityConfigToMldev( - ApiClient apiClient, 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 proactivityConfigToVertex( - ApiClient apiClient, 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 liveConnectConfigToMldev( - ApiClient apiClient, 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"}, - speechConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tLiveSpeechConfig( - this.apiClient, - 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"}, - contentToMldev( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tContent( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), toObject)); } if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { ArrayNode keyArray = (ArrayNode) - Transformers.tTools( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"tools"})); + Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add( - toolToMldev( - apiClient, - JsonSerializable.toJsonNode(Transformers.tTool(this.apiClient, item)), - toObject)); + result.add(toolToMldev(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); } Common.setValueByPath(parentObject, new String[] {"setup", "tools"}, result); } @@ -1603,7 +1060,6 @@ ObjectNode liveConnectConfigToMldev( parentObject, new String[] {"setup", "sessionResumption"}, sessionResumptionConfigToMldev( - apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"sessionResumption"})), toObject)); @@ -1614,7 +1070,6 @@ ObjectNode liveConnectConfigToMldev( parentObject, new String[] {"setup", "inputAudioTranscription"}, audioTranscriptionConfigToMldev( - apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})), toObject)); @@ -1625,7 +1080,6 @@ ObjectNode liveConnectConfigToMldev( parentObject, new String[] {"setup", "outputAudioTranscription"}, audioTranscriptionConfigToMldev( - apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})), toObject)); @@ -1635,42 +1089,61 @@ ObjectNode liveConnectConfigToMldev( Common.setValueByPath( parentObject, new String[] {"setup", "realtimeInputConfig"}, - realtimeInputConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})); } if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { Common.setValueByPath( parentObject, new String[] {"setup", "contextWindowCompression"}, - contextWindowCompressionConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})); } if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { Common.setValueByPath( parentObject, new String[] {"setup", "proactivity"}, - proactivityConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"proactivity"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"proactivity"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"explicitVadSignal"}))) { + throw new IllegalArgumentException( + "explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"avatarConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"setup", "avatarConfig"}, + Common.getValueByPath(fromObject, new String[] {"avatarConfig"})); + } + + 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[] {"setup", "safetySettings"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"streamTranslationConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"setup", "generationConfig", "streamTranslationConfig"}, + Common.getValueByPath(fromObject, new String[] {"streamTranslationConfig"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveConnectConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode liveConnectConfigToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { Common.setValueByPath( @@ -1725,13 +1198,15 @@ ObjectNode liveConnectConfigToVertex( Common.setValueByPath( parentObject, new String[] {"setup", "generationConfig", "speechConfig"}, - speechConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tLiveSpeechConfig( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"speechConfig"}))), - toObject)); + Transformers.tLiveSpeechConfig( + Common.getValueByPath(fromObject, new String[] {"speechConfig"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"setup", "generationConfig", "thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { @@ -1746,10 +1221,8 @@ ObjectNode liveConnectConfigToVertex( parentObject, new String[] {"setup", "systemInstruction"}, contentToVertex( - apiClient, JsonSerializable.toJsonNode( Transformers.tContent( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), toObject)); } @@ -1757,17 +1230,12 @@ ObjectNode liveConnectConfigToVertex( if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { ArrayNode keyArray = (ArrayNode) - Transformers.tTools( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"tools"})); + Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add( - toolToVertex( - apiClient, - JsonSerializable.toJsonNode(Transformers.tTool(this.apiClient, item)), - toObject)); + result.add(toolToVertex(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); } Common.setValueByPath(parentObject, new String[] {"setup", "tools"}, result); } @@ -1776,66 +1244,70 @@ ObjectNode liveConnectConfigToVertex( Common.setValueByPath( parentObject, new String[] {"setup", "sessionResumption"}, - sessionResumptionConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"sessionResumption"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"sessionResumption"})); } if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { Common.setValueByPath( parentObject, new String[] {"setup", "inputAudioTranscription"}, - audioTranscriptionConfigToVertex( - apiClient, - 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( parentObject, new String[] {"setup", "outputAudioTranscription"}, - audioTranscriptionConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})); } if (Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"}) != null) { Common.setValueByPath( parentObject, new String[] {"setup", "realtimeInputConfig"}, - realtimeInputConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})); } if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { Common.setValueByPath( parentObject, new String[] {"setup", "contextWindowCompression"}, - contextWindowCompressionConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})); } if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { Common.setValueByPath( parentObject, new String[] {"setup", "proactivity"}, - proactivityConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"proactivity"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"proactivity"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"explicitVadSignal"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"setup", "explicitVadSignal"}, + Common.getValueByPath(fromObject, new String[] {"explicitVadSignal"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"avatarConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"setup", "avatarConfig"}, + Common.getValueByPath(fromObject, new String[] {"avatarConfig"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"safetySettings"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"setup", "safetySettings"}, + Common.getValueByPath(fromObject, new String[] {"safetySettings"})); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"streamTranslationConfig"}))) { + throw new IllegalArgumentException( + "streamTranslationConfig parameter is only supported in Gemini Developer API mode, not in" + + " Gemini Enterprise Agent Platform mode."); } return toObject; @@ -1844,7 +1316,7 @@ ObjectNode liveConnectConfigToVertex( @ExcludeFromGeneratedCoverageReport ObjectNode liveConnectParametersToMldev( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, @@ -1858,7 +1330,6 @@ ObjectNode liveConnectParametersToMldev( toObject, new String[] {"config"}, liveConnectConfigToMldev( - apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), toObject)); @@ -1870,7 +1341,7 @@ ObjectNode liveConnectParametersToMldev( @ExcludeFromGeneratedCoverageReport ObjectNode liveConnectParametersToVertex( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, @@ -1884,7 +1355,6 @@ ObjectNode liveConnectParametersToVertex( toObject, new String[] {"config"}, liveConnectConfigToVertex( - apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), toObject)); @@ -1894,55 +1364,31 @@ ObjectNode liveConnectParametersToVertex( } @ExcludeFromGeneratedCoverageReport - ObjectNode activityStartToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + 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(); - return toObject; - } + for (JsonNode item : keyArray) { + result.add(blobToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"mediaChunks"}, result); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode activityStartToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode activityEndToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode activityEndToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveSendRealtimeInputParametersToMldev( - ApiClient apiClient, 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( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"media"}))); - } - - if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"audio"}, - Transformers.tAudioBlob( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"audio"}))); - } + if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"audio"}, + blobToMldev( + JsonSerializable.toJsonNode( + Transformers.tAudioBlob( + Common.getValueByPath(fromObject, new String[] {"audio"}))), + toObject)); + } if (Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}) != null) { Common.setValueByPath( @@ -1955,8 +1401,11 @@ ObjectNode liveSendRealtimeInputParametersToMldev( Common.setValueByPath( toObject, new String[] {"video"}, - Transformers.tImageBlob( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"video"}))); + blobToMldev( + JsonSerializable.toJsonNode( + Transformers.tImageBlob( + Common.getValueByPath(fromObject, new String[] {"video"}))), + toObject)); } if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { @@ -1970,41 +1419,34 @@ ObjectNode liveSendRealtimeInputParametersToMldev( Common.setValueByPath( toObject, new String[] {"activityStart"}, - activityStartToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityStart"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"activityStart"})); } if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { Common.setValueByPath( toObject, new String[] {"activityEnd"}, - activityEndToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityEnd"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"activityEnd"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveSendRealtimeInputParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + 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( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"media"}))); + Transformers.tBlobs(Common.getValueByPath(fromObject, new String[] {"media"}))); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audio"}))) { - throw new IllegalArgumentException("audio parameter is not supported in Vertex AI."); + 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) { @@ -2014,151 +1456,103 @@ ObjectNode liveSendRealtimeInputParametersToVertex( Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"video"}))) { - throw new IllegalArgumentException("video parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"video"}, + Transformers.tImageBlob(Common.getValueByPath(fromObject, new String[] {"video"}))); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"text"}))) { - throw new IllegalArgumentException("text parameter is not supported in Vertex AI."); + 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( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityStart"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"activityStart"})); } if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { Common.setValueByPath( toObject, new String[] {"activityEnd"}, - activityEndToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityEnd"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"activityEnd"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientSetupToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + ObjectNode liveServerMessageFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"setupComplete"}) != null) { Common.setValueByPath( toObject, - new String[] {"model"}, - Common.getValueByPath(fromObject, new String[] {"model"})); + new String[] {"setupComplete"}, + Common.getValueByPath(fromObject, new String[] {"setupComplete"})); } - if (Common.getValueByPath(fromObject, new String[] {"generationConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"serverContent"}) != null) { Common.setValueByPath( toObject, - new String[] {"generationConfig"}, - Common.getValueByPath(fromObject, new String[] {"generationConfig"})); + new String[] {"serverContent"}, + Common.getValueByPath(fromObject, new String[] {"serverContent"})); } - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"systemInstruction"}, - contentToMldev( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tContent( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tTools( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"tools"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add( - toolToMldev( - apiClient, - JsonSerializable.toJsonNode(Transformers.tTool(this.apiClient, item)), - toObject)); - } - Common.setValueByPath(toObject, new String[] {"tools"}, result); + new String[] {"toolCall"}, + Common.getValueByPath(fromObject, new String[] {"toolCall"})); } - if (Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"}) != null) { Common.setValueByPath( toObject, - new String[] {"realtimeInputConfig"}, - realtimeInputConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})), - toObject)); + new String[] {"toolCallCancellation"}, + Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"})); } - if (Common.getValueByPath(fromObject, new String[] {"sessionResumption"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"sessionResumption"}, - sessionResumptionConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"sessionResumption"})), - toObject)); + new String[] {"usageMetadata"}, + Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); } - if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"goAway"}) != null) { Common.setValueByPath( toObject, - new String[] {"contextWindowCompression"}, - contextWindowCompressionConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})), - toObject)); + new String[] {"goAway"}, + Common.getValueByPath(fromObject, new String[] {"goAway"})); } - if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"}) != null) { Common.setValueByPath( toObject, - new String[] {"inputAudioTranscription"}, - audioTranscriptionConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})), - toObject)); + new String[] {"sessionResumptionUpdate"}, + Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"voiceActivityDetectionSignal"}) != null) { Common.setValueByPath( toObject, - new String[] {"outputAudioTranscription"}, - audioTranscriptionConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})), - toObject)); + new String[] {"voiceActivityDetectionSignal"}, + Common.getValueByPath(fromObject, new String[] {"voiceActivityDetectionSignal"})); } - if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"voiceActivity"}) != null) { Common.setValueByPath( toObject, - new String[] {"proactivity"}, - proactivityConfigToMldev( - apiClient, + new String[] {"voiceActivity"}, + voiceActivityFromMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"proactivity"})), + Common.getValueByPath(fromObject, new String[] {"voiceActivity"})), toObject)); } @@ -2166,117 +1560,74 @@ ObjectNode liveClientSetupToMldev( } @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientSetupToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + ObjectNode liveServerMessageFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"setupComplete"}) != null) { Common.setValueByPath( toObject, - new String[] {"model"}, - Common.getValueByPath(fromObject, new String[] {"model"})); + new String[] {"setupComplete"}, + Common.getValueByPath(fromObject, new String[] {"setupComplete"})); } - if (Common.getValueByPath(fromObject, new String[] {"generationConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"serverContent"}) != null) { Common.setValueByPath( toObject, - new String[] {"generationConfig"}, - Common.getValueByPath(fromObject, new String[] {"generationConfig"})); + new String[] {"serverContent"}, + Common.getValueByPath(fromObject, new String[] {"serverContent"})); } - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"systemInstruction"}, - contentToVertex( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tContent( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tTools( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"tools"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add( - toolToVertex( - apiClient, - JsonSerializable.toJsonNode(Transformers.tTool(this.apiClient, item)), - toObject)); - } - Common.setValueByPath(toObject, new String[] {"tools"}, result); + new String[] {"toolCall"}, + Common.getValueByPath(fromObject, new String[] {"toolCall"})); } - if (Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"}) != null) { Common.setValueByPath( toObject, - new String[] {"realtimeInputConfig"}, - realtimeInputConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})), - toObject)); + new String[] {"toolCallCancellation"}, + Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"})); } - if (Common.getValueByPath(fromObject, new String[] {"sessionResumption"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"sessionResumption"}, - sessionResumptionConfigToVertex( - apiClient, + new String[] {"usageMetadata"}, + usageMetadataFromVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"sessionResumption"})), + Common.getValueByPath(fromObject, new String[] {"usageMetadata"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"goAway"}) != null) { Common.setValueByPath( toObject, - new String[] {"contextWindowCompression"}, - contextWindowCompressionConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})), - toObject)); + new String[] {"goAway"}, + Common.getValueByPath(fromObject, new String[] {"goAway"})); } - if (Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"}) != null) { Common.setValueByPath( toObject, - new String[] {"inputAudioTranscription"}, - audioTranscriptionConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})), - toObject)); + new String[] {"sessionResumptionUpdate"}, + Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"voiceActivityDetectionSignal"}) != null) { Common.setValueByPath( toObject, - new String[] {"outputAudioTranscription"}, - audioTranscriptionConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})), - toObject)); + new String[] {"voiceActivityDetectionSignal"}, + Common.getValueByPath(fromObject, new String[] {"voiceActivityDetectionSignal"})); } - if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"voiceActivity"}) != null) { Common.setValueByPath( toObject, - new String[] {"proactivity"}, - proactivityConfigToVertex( - apiClient, + new String[] {"voiceActivity"}, + voiceActivityFromVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"proactivity"})), + Common.getValueByPath(fromObject, new String[] {"voiceActivity"})), toObject)); } @@ -2284,1323 +1635,448 @@ ObjectNode liveClientSetupToVertex( } @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientContentToMldev( - ApiClient apiClient, 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"turns"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"turnComplete"}) != null) { + ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( toObject, - new String[] {"turnComplete"}, - Common.getValueByPath(fromObject, new String[] {"turnComplete"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientContentToVertex( - ApiClient apiClient, 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"turns"}, result); + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"turnComplete"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { Common.setValueByPath( toObject, - new String[] {"turnComplete"}, - Common.getValueByPath(fromObject, new String[] {"turnComplete"})); + new String[] {"codeExecutionResult"}, + Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientRealtimeInputToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mediaChunks"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { Common.setValueByPath( toObject, - new String[] {"mediaChunks"}, - Common.getValueByPath(fromObject, new String[] {"mediaChunks"})); + new String[] {"executableCode"}, + Common.getValueByPath(fromObject, new String[] {"executableCode"})); } - if (Common.getValueByPath(fromObject, new String[] {"audio"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { Common.setValueByPath( toObject, - new String[] {"audio"}, - Common.getValueByPath(fromObject, new String[] {"audio"})); + new String[] {"fileData"}, + fileDataToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"fileData"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"audioStreamEnd"}, - Common.getValueByPath(fromObject, new String[] {"audioStreamEnd"})); + new String[] {"functionCall"}, + functionCallToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"functionCall"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"video"}, - Common.getValueByPath(fromObject, new String[] {"video"})); + new String[] {"functionResponse"}, + Common.getValueByPath(fromObject, new String[] {"functionResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != 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"}, - activityStartToMldev( - apiClient, + new String[] {"inlineData"}, + blobToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityStart"})), + Common.getValueByPath(fromObject, new String[] {"inlineData"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( toObject, - new String[] {"activityEnd"}, - activityEndToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityEnd"})), - toObject)); + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientRealtimeInputToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mediaChunks"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { Common.setValueByPath( toObject, - new String[] {"mediaChunks"}, - Common.getValueByPath(fromObject, new String[] {"mediaChunks"})); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audio"}))) { - throw new IllegalArgumentException("audio parameter is not supported in Vertex AI."); + new String[] {"thought"}, + Common.getValueByPath(fromObject, new String[] {"thought"})); } - 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[] {"thoughtSignature"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"thoughtSignature"}, + Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"video"}))) { - throw new IllegalArgumentException("video parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"videoMetadata"}, + Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"text"}))) { - throw new IllegalArgumentException("text parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"toolCall"}, + Common.getValueByPath(fromObject, new String[] {"toolCall"})); } - if (Common.getValueByPath(fromObject, new String[] {"activityStart"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"activityStart"}, - activityStartToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityStart"})), - toObject)); + new String[] {"toolResponse"}, + Common.getValueByPath(fromObject, new String[] {"toolResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"activityEnd"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"partMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"activityEnd"}, - activityEndToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"activityEnd"})), - toObject)); + new String[] {"partMetadata"}, + Common.getValueByPath(fromObject, new String[] {"partMetadata"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode functionResponseToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"willContinue"}) != null) { + ObjectNode partToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( toObject, - new String[] {"willContinue"}, - Common.getValueByPath(fromObject, new String[] {"willContinue"})); + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"scheduling"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { Common.setValueByPath( toObject, - new String[] {"scheduling"}, - Common.getValueByPath(fromObject, new String[] {"scheduling"})); + new String[] {"codeExecutionResult"}, + Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); } - if (Common.getValueByPath(fromObject, new String[] {"id"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { Common.setValueByPath( - toObject, new String[] {"id"}, Common.getValueByPath(fromObject, new String[] {"id"})); + toObject, + new String[] {"executableCode"}, + Common.getValueByPath(fromObject, new String[] {"executableCode"})); } - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"fileData"}, + Common.getValueByPath(fromObject, new String[] {"fileData"})); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); + new String[] {"functionCall"}, + Common.getValueByPath(fromObject, new String[] {"functionCall"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionResponseToVertex( - ApiClient apiClient, 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.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[] {"scheduling"}))) { - throw new IllegalArgumentException("scheduling parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"inlineData"}, + Common.getValueByPath(fromObject, new String[] {"inlineData"})); } - if (Common.getValueByPath(fromObject, new String[] {"id"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( - toObject, new String[] {"id"}, Common.getValueByPath(fromObject, new String[] {"id"})); + toObject, + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"thought"}, + Common.getValueByPath(fromObject, new String[] {"thought"})); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { Common.setValueByPath( toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); + new String[] {"thoughtSignature"}, + Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientToolResponseToMldev( - ApiClient apiClient, 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(functionResponseToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionResponses"}, result); + if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"videoMetadata"}, + Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"toolCall"}))) { + throw new IllegalArgumentException( + "toolCall parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientToolResponseToVertex( - ApiClient apiClient, 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(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"toolResponse"}))) { + throw new IllegalArgumentException( + "toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } - for (JsonNode item : keyArray) { - result.add( - functionResponseToVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionResponses"}, result); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"partMetadata"}))) { + throw new IllegalArgumentException( + "partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientMessageToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"setup"}) != null) { + ObjectNode safetySettingToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"category"}) != null) { Common.setValueByPath( toObject, - new String[] {"setup"}, - liveClientSetupToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"setup"})), - toObject)); + new String[] {"category"}, + Common.getValueByPath(fromObject, new String[] {"category"})); } - if (Common.getValueByPath(fromObject, new String[] {"clientContent"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"clientContent"}, - liveClientContentToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"clientContent"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"method"}))) { + throw new IllegalArgumentException( + "method parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"realtimeInput"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"threshold"}) != null) { Common.setValueByPath( toObject, - new String[] {"realtimeInput"}, - liveClientRealtimeInputToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInput"})), - toObject)); + new String[] {"threshold"}, + Common.getValueByPath(fromObject, new String[] {"threshold"})); } - if (Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode sessionResumptionConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"handle"}) != null) { Common.setValueByPath( toObject, - new String[] {"realtime_input"}, - liveSendRealtimeInputParametersToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"})), - toObject)); + new String[] {"handle"}, + Common.getValueByPath(fromObject, new String[] {"handle"})); } - if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"toolResponse"}, - liveClientToolResponseToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolResponse"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"transparent"}))) { + throw new IllegalArgumentException( + "transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveClientMessageToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"setup"}) != null) { + ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { + throw new IllegalArgumentException( + "retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { Common.setValueByPath( toObject, - new String[] {"setup"}, - liveClientSetupToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"setup"})), - toObject)); + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); } - if (Common.getValueByPath(fromObject, new String[] {"clientContent"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"clientContent"}, - liveClientContentToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"clientContent"})), - toObject)); + new String[] {"fileSearch"}, + Common.getValueByPath(fromObject, new String[] {"fileSearch"})); } - if (Common.getValueByPath(fromObject, new String[] {"realtimeInput"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"realtimeInput"}, - liveClientRealtimeInputToVertex( - apiClient, + new String[] {"googleSearch"}, + googleSearchToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInput"})), + Common.getValueByPath(fromObject, new String[] {"googleSearch"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { Common.setValueByPath( toObject, - new String[] {"realtime_input"}, - liveSendRealtimeInputParametersToVertex( - apiClient, + new String[] {"googleMaps"}, + googleMapsToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputParameters"})), + Common.getValueByPath(fromObject, new String[] {"googleMaps"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { Common.setValueByPath( toObject, - new String[] {"toolResponse"}, - liveClientToolResponseToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolResponse"})), - toObject)); + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerSetupCompleteFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerSetupCompleteFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataFromMldev( - ApiClient apiClient, 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[] {"enterpriseWebSearch"}))) { + throw new IllegalArgumentException( + "enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataFromVertex( - ApiClient apiClient, 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[] {"parallelAiSearch"}))) { + throw new IllegalArgumentException( + "parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mcpServers"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"mcpServers"}, + Common.getValueByPath(fromObject, new String[] {"mcpServers"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode blobFromMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { + ObjectNode toolToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"retrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + new String[] {"retrieval"}, + Common.getValueByPath(fromObject, new String[] {"retrieval"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode blobFromVertex(ApiClient apiClient, 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) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataFromMldev(ApiClient apiClient, 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 fileDataFromVertex(ApiClient apiClient, 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[] {"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(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataFromMldev( - apiClient, - 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( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataFromMldev( - apiClient, - 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 partFromVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataFromVertex( - apiClient, - 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"}, - blobFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataFromVertex( - apiClient, - 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(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(); - - for (JsonNode item : keyArray) { - result.add(partFromMldev(apiClient, 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 contentFromVertex(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(); - - for (JsonNode item : keyArray) { - result.add(partFromVertex(apiClient, 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( - ApiClient apiClient, 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 transcriptionFromVertex( - ApiClient apiClient, 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( - ApiClient apiClient, 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 urlMetadataFromVertex( - ApiClient apiClient, 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( - ApiClient apiClient, 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"urlMetadata"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextMetadataFromVertex( - ApiClient apiClient, 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(urlMetadataFromVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"urlMetadata"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerContentFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"modelTurn"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"modelTurn"}, - contentFromMldev( - apiClient, - 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( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inputTranscription"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputTranscription"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"outputTranscription"}, - transcriptionFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputTranscription"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"urlContextMetadata"}, - urlContextMetadataFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerContentFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"modelTurn"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"modelTurn"}, - contentFromVertex( - apiClient, - 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"}, - transcriptionFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inputTranscription"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"outputTranscription"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"outputTranscription"}, - transcriptionFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"outputTranscription"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionCallFromMldev( - ApiClient apiClient, 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 functionCallFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - 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( - ApiClient apiClient, 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionCalls"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerToolCallFromVertex( - ApiClient apiClient, 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionCalls"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerToolCallCancellationFromMldev( - ApiClient apiClient, 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 liveServerToolCallCancellationFromVertex( - ApiClient apiClient, 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( - ApiClient apiClient, 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 modalityTokenCountFromVertex( - ApiClient apiClient, 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( - ApiClient apiClient, 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"})); + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); } - if (Common.getValueByPath(fromObject, new String[] {"cachedContentTokenCount"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"fileSearch"}))) { + throw new IllegalArgumentException( + "fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"cachedContentTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"cachedContentTokenCount"})); + new String[] {"googleSearch"}, + Common.getValueByPath(fromObject, new String[] {"googleSearch"})); } - if (Common.getValueByPath(fromObject, new String[] {"responseTokenCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"responseTokenCount"})); + new String[] {"googleMaps"}, + Common.getValueByPath(fromObject, new String[] {"googleMaps"})); } - if (Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokenCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { Common.setValueByPath( toObject, - new String[] {"toolUsePromptTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokenCount"})); + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtsTokenCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"thoughtsTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"thoughtsTokenCount"})); + new String[] {"enterpriseWebSearch"}, + Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})); } - if (Common.getValueByPath(fromObject, new String[] {"totalTokenCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { Common.setValueByPath( toObject, - new String[] {"totalTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"totalTokenCount"})); + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); } - 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"promptTokensDetails"}, result); + 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[] {"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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"cacheTokensDetails"}, result); + if (Common.getValueByPath(fromObject, new String[] {"parallelAiSearch"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"parallelAiSearch"}, + Common.getValueByPath(fromObject, new String[] {"parallelAiSearch"})); } - 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"responseTokensDetails"}, result); + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); } - 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( - modalityTokenCountFromMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"toolUsePromptTokensDetails"}, result); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"mcpServers"}))) { + throw new IllegalArgumentException( + "mcpServers parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode usageMetadataFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode usageMetadataFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"promptTokenCount"}) != null) { Common.setValueByPath( toObject, @@ -3644,317 +2120,64 @@ ObjectNode usageMetadataFromVertex( } 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(apiClient, 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(apiClient, 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(apiClient, 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(apiClient, 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 liveServerGoAwayFromMldev( - ApiClient apiClient, 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 liveServerGoAwayFromVertex( - ApiClient apiClient, 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 liveServerSessionResumptionUpdateFromMldev( - ApiClient apiClient, 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"})); + new String[] {"promptTokensDetails"}, + Common.getValueByPath(fromObject, new String[] {"promptTokensDetails"})); } - if (Common.getValueByPath(fromObject, new String[] {"lastConsumedClientMessageIndex"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"cacheTokensDetails"}) != null) { Common.setValueByPath( toObject, - new String[] {"lastConsumedClientMessageIndex"}, - Common.getValueByPath(fromObject, new String[] {"lastConsumedClientMessageIndex"})); + new String[] {"cacheTokensDetails"}, + Common.getValueByPath(fromObject, new String[] {"cacheTokensDetails"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerSessionResumptionUpdateFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"newHandle"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"candidatesTokensDetails"}) != null) { Common.setValueByPath( toObject, - new String[] {"newHandle"}, - Common.getValueByPath(fromObject, new String[] {"newHandle"})); + new String[] {"responseTokensDetails"}, + Common.getValueByPath(fromObject, new String[] {"candidatesTokensDetails"})); } - if (Common.getValueByPath(fromObject, new String[] {"resumable"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokensDetails"}) != null) { Common.setValueByPath( toObject, - new String[] {"resumable"}, - Common.getValueByPath(fromObject, new String[] {"resumable"})); + new String[] {"toolUsePromptTokensDetails"}, + Common.getValueByPath(fromObject, new String[] {"toolUsePromptTokensDetails"})); } - if (Common.getValueByPath(fromObject, new String[] {"lastConsumedClientMessageIndex"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"trafficType"}) != null) { Common.setValueByPath( toObject, - new String[] {"lastConsumedClientMessageIndex"}, - Common.getValueByPath(fromObject, new String[] {"lastConsumedClientMessageIndex"})); + new String[] {"trafficType"}, + Common.getValueByPath(fromObject, new String[] {"trafficType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerMessageFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"setupComplete"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"setupComplete"}, - liveServerSetupCompleteFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"setupComplete"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"serverContent"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"serverContent"}, - liveServerContentFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"serverContent"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"toolCall"}, - liveServerToolCallFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolCall"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"toolCallCancellation"}, - liveServerToolCallCancellationFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"usageMetadata"}, - usageMetadataFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"goAway"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"goAway"}, - liveServerGoAwayFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"goAway"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"}) != null) { + ObjectNode voiceActivityFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"type"}) != null) { Common.setValueByPath( toObject, - new String[] {"sessionResumptionUpdate"}, - liveServerSessionResumptionUpdateFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"})), - toObject)); + new String[] {"voiceActivityType"}, + Common.getValueByPath(fromObject, new String[] {"type"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveServerMessageFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"setupComplete"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"setupComplete"}, - liveServerSetupCompleteFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"setupComplete"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"serverContent"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"serverContent"}, - liveServerContentFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"serverContent"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"toolCall"}, - liveServerToolCallFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolCall"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"toolCallCancellation"}, - liveServerToolCallCancellationFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolCallCancellation"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"usageMetadata"}, - usageMetadataFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"goAway"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"goAway"}, - liveServerGoAwayFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"goAway"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"}) != null) { + ObjectNode voiceActivityFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"type"}) != null) { Common.setValueByPath( toObject, - new String[] {"sessionResumptionUpdate"}, - liveServerSessionResumptionUpdateFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"sessionResumptionUpdate"})), - toObject)); + new String[] {"voiceActivityType"}, + Common.getValueByPath(fromObject, new String[] {"type"})); } 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..e38fae77ed8 --- /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.TokensInfo; +import com.google.genai.types.Tool; +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-2.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..c5c9131983a --- /dev/null +++ b/src/main/java/com/google/genai/LocalTokenizerLoader.java @@ -0,0 +1,305 @@ +/* + * 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 java.util.logging.Logger; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + +/** + * 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-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"); + modelMap.put("gemini-3-pro-preview", "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..c2d3017250c --- /dev/null +++ b/src/main/java/com/google/genai/LocalTokenizerProcessor.java @@ -0,0 +1,458 @@ +/* + * 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.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; +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; + +// 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 94baff7bebf..324156777ca 100644 --- a/src/main/java/com/google/genai/Models.java +++ b/src/main/java/com/google/genai/Models.java @@ -24,6 +24,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode; 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; @@ -39,8 +41,9 @@ import com.google.genai.types.EditImageParameters; import com.google.genai.types.EditImageResponse; import com.google.genai.types.EmbedContentConfig; -import com.google.genai.types.EmbedContentParameters; +import com.google.genai.types.EmbedContentParametersPrivate; import com.google.genai.types.EmbedContentResponse; +import com.google.genai.types.EmbeddingApiType; import com.google.genai.types.GenerateContentConfig; import com.google.genai.types.GenerateContentParameters; import com.google.genai.types.GenerateContentResponse; @@ -50,34 +53,47 @@ 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; import com.google.genai.types.HttpOptions; +import com.google.genai.types.HttpResponse; import com.google.genai.types.Image; import com.google.genai.types.ListModelsConfig; import com.google.genai.types.ListModelsParameters; 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; import com.google.genai.types.UpscaleImageAPIParameters; import com.google.genai.types.UpscaleImageConfig; import com.google.genai.types.UpscaleImageResponse; +import com.google.genai.types.Video; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.logging.Logger; -import org.apache.http.HttpEntity; -import org.apache.http.util.EntityUtils; +import okhttp3.Headers; +import okhttp3.ResponseBody; /** * Provides methods for interacting with the available GenAI models. Instantiating this class is not @@ -85,6 +101,7 @@ * `client.models.methodName(...)` directly. */ public final class Models { + final ApiClient apiClient; public Models(ApiClient apiClient) { @@ -92,67 +109,105 @@ public Models(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToMldev( - ApiClient apiClient, 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 only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode.", + 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 only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode.", + enumValue)); + } + } + + @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 only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode.", + enumValue)); } + } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode authConfigToMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"apiKey"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"apiKey"}, + Common.getValueByPath(fromObject, new String[] {"apiKey"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}))) { + throw new IllegalArgumentException( + "apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode blobToMldev(ApiClient apiClient, 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.isZero(Common.getValueByPath(fromObject, new String[] {"authType"}))) { + throw new IllegalArgumentException( + "authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - 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[] {"googleServiceAccountConfig"}))) { + throw new IllegalArgumentException( + "googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent" + + " Platform mode, not in Gemini Developer API mode."); } - 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[] {"httpBasicAuthConfig"}))) { + throw new IllegalArgumentException( + "httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"oauthConfig"}))) { + throw new IllegalArgumentException( + "oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"oidcConfig"}))) { + throw new IllegalArgumentException( + "oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToMldev(ApiClient apiClient, 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) { + ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + new String[] {"data"}, + Common.getValueByPath(fromObject, new String[] {"data"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException( + "displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { @@ -166,831 +221,1212 @@ ObjectNode fileDataToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode } @ExcludeFromGeneratedCoverageReport - ObjectNode partToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + ObjectNode candidateFromMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"content"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataToMldev( - apiClient, - 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, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"tokenCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"inlineData"}, - blobToMldev( - apiClient, - 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( - apiClient, - 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[] {"groundingMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + new String[] {"groundingMetadata"}, + Common.getValueByPath(fromObject, new String[] {"groundingMetadata"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"avgLogprobs"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + new String[] {"avgLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"avgLogprobs"})); } - 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(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(); - - for (JsonNode item : keyArray) { - result.add(partToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { + ObjectNode citationMetadataFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"anyOf"}) != null) { + ObjectNode computeTokensParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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) { - Common.setValueByPath( - toObject, - new String[] {"default"}, - Common.getValueByPath(fromObject, new String[] {"default"})); - } + 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[] {"description"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + for (JsonNode item : keyArray) { + result.add(contentToVertex(JsonSerializable.toJsonNode(item), toObject, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"contents"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"enum"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"enum"}, - Common.getValueByPath(fromObject, new String[] {"enum"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"example"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode computeTokensResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"example"}, - Common.getValueByPath(fromObject, new String[] {"example"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"format"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"tokensInfo"}) != null) { Common.setValueByPath( toObject, - new String[] {"format"}, - Common.getValueByPath(fromObject, new String[] {"format"})); + new String[] {"tokensInfo"}, + Common.getValueByPath(fromObject, new String[] {"tokensInfo"})); } - if (Common.getValueByPath(fromObject, new String[] {"items"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"items"}, - Common.getValueByPath(fromObject, new String[] {"items"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"maxItems"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode contentEmbeddingFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"values"}) != null) { Common.setValueByPath( toObject, - new String[] {"maxItems"}, - Common.getValueByPath(fromObject, new String[] {"maxItems"})); + new String[] {"values"}, + Common.getValueByPath(fromObject, new String[] {"values"})); } - if (Common.getValueByPath(fromObject, new String[] {"maxLength"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"statistics"}) != null) { Common.setValueByPath( toObject, - new String[] {"maxLength"}, - Common.getValueByPath(fromObject, new String[] {"maxLength"})); + new String[] {"statistics"}, + contentEmbeddingStatisticsFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"statistics"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"maxProperties"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"maxProperties"}, - Common.getValueByPath(fromObject, new String[] {"maxProperties"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"maximum"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode contentEmbeddingStatisticsFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"truncated"}) != null) { Common.setValueByPath( toObject, - new String[] {"maximum"}, - Common.getValueByPath(fromObject, new String[] {"maximum"})); + new String[] {"truncated"}, + Common.getValueByPath(fromObject, new String[] {"truncated"})); } - if (Common.getValueByPath(fromObject, new String[] {"minItems"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"token_count"}) != null) { Common.setValueByPath( toObject, - new String[] {"minItems"}, - Common.getValueByPath(fromObject, new String[] {"minItems"})); + new String[] {"tokenCount"}, + Common.getValueByPath(fromObject, new String[] {"token_count"})); } - if (Common.getValueByPath(fromObject, new String[] {"minLength"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"minLength"}, - Common.getValueByPath(fromObject, new String[] {"minLength"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"minProperties"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"minProperties"}, - Common.getValueByPath(fromObject, new String[] {"minProperties"})); - } + @ExcludeFromGeneratedCoverageReport + ObjectNode contentToMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"minimum"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"minimum"}, - Common.getValueByPath(fromObject, new String[] {"minimum"})); + for (JsonNode item : keyArray) { + result.add(partToMldev(JsonSerializable.toJsonNode(item), toObject, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"parts"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"nullable"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { Common.setValueByPath( toObject, - new String[] {"nullable"}, - Common.getValueByPath(fromObject, new String[] {"nullable"})); + new String[] {"role"}, + Common.getValueByPath(fromObject, new String[] {"role"})); } - if (Common.getValueByPath(fromObject, new String[] {"pattern"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"pattern"}, - Common.getValueByPath(fromObject, new String[] {"pattern"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"properties"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"properties"}, - Common.getValueByPath(fromObject, new String[] {"properties"})); - } + @ExcludeFromGeneratedCoverageReport + ObjectNode contentToVertex(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"propertyOrdering"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"propertyOrdering"}, - Common.getValueByPath(fromObject, new String[] {"propertyOrdering"})); + for (JsonNode item : keyArray) { + result.add(partToVertex(JsonSerializable.toJsonNode(item), toObject, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"parts"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"required"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { Common.setValueByPath( toObject, - new String[] {"required"}, - Common.getValueByPath(fromObject, new String[] {"required"})); + new String[] {"role"}, + Common.getValueByPath(fromObject, new String[] {"role"})); } - if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode controlReferenceConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"controlType"}) != null) { Common.setValueByPath( toObject, - new String[] {"title"}, - Common.getValueByPath(fromObject, new String[] {"title"})); + new String[] {"controlType"}, + Common.getValueByPath(fromObject, new String[] {"controlType"})); } - if (Common.getValueByPath(fromObject, new String[] {"type"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableControlImageComputation"}) != null) { Common.setValueByPath( toObject, - new String[] {"type"}, - Common.getValueByPath(fromObject, new String[] {"type"})); + new String[] {"computeControl"}, + Common.getValueByPath(fromObject, new String[] {"enableControlImageComputation"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode modelSelectionConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero( - Common.getValueByPath(fromObject, new String[] {"featureSelectionPreference"}))) { + ObjectNode countTokensConfigToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))) { + throw new IllegalArgumentException( + "systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"tools"}))) { + throw new IllegalArgumentException( + "tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"generationConfig"}))) { throw new IllegalArgumentException( - "featureSelectionPreference parameter is not supported in Gemini API."); + "generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode safetySettingToMldev( - ApiClient apiClient, 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."); - } + ObjectNode countTokensConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); - 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"}, + contentToVertex( + JsonSerializable.toJsonNode( + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), + toObject, + rootObject)); } - 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, rootObject)); + } + 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, + rootObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"behavior"}) != null) { + ObjectNode countTokensParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"contents"}, result); } - 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[] {"config"}) != null) { + JsonNode unused = + countTokensConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } - if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode countTokensParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - 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[] {"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, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"contents"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + countTokensConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { + ObjectNode countTokensResponseFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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( - 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[] {"cachedContentTokenCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"timeRangeFilter"}, - intervalToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); + new String[] {"cachedContentTokenCount"}, + Common.getValueByPath(fromObject, new String[] {"cachedContentTokenCount"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + ObjectNode countTokensResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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) { + if (Common.getValueByPath(fromObject, new String[] {"totalTokens"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); + new String[] {"totalTokens"}, + Common.getValueByPath(fromObject, new String[] {"totalTokens"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { + ObjectNode deleteModelParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), - toObject)); + new String[] {"_url", "name"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode enterpriseWebSearchToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode deleteModelParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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 apiKeyConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyString"}))) { - throw new IllegalArgumentException("apiKeyString parameter is not supported in Gemini API."); + ObjectNode deleteModelResponseFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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 authConfigToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}))) { - throw new IllegalArgumentException("apiKeyConfig parameter is not supported in Gemini API."); - } - - if (Common.getValueByPath(fromObject, new String[] {"authType"}) != null) { + ObjectNode deleteModelResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"authType"}, - Common.getValueByPath(fromObject, new String[] {"authType"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode editImageConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleServiceAccountConfig"}, - Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"})); + parentObject, + new String[] {"parameters", "storageUri"}, + Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"httpBasicAuthConfig"}, - Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"})); + parentObject, + new String[] {"parameters", "negativePrompt"}, + Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"oauthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { Common.setValueByPath( - toObject, - new String[] {"oauthConfig"}, - Common.getValueByPath(fromObject, new String[] {"oauthConfig"})); + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); } - if (Common.getValueByPath(fromObject, new String[] {"oidcConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( - toObject, - new String[] {"oidcConfig"}, - Common.getValueByPath(fromObject, new String[] {"oidcConfig"})); + parentObject, + new String[] {"parameters", "aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleMapsToMldev(ApiClient apiClient, 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[] {"guidanceScale"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "guidanceScale"}, + Common.getValueByPath(fromObject, new String[] {"guidanceScale"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolToMldev(ApiClient apiClient, 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(); + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); + } - for (JsonNode item : keyArray) { - result.add( - functionDeclarationToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); + if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "safetySetting"}, + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); } - 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[] {"personGeneration"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleSearch"}, - googleSearchToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); + parentObject, + new String[] {"parameters", "includeSafetyAttributes"}, + Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - toObject)); + parentObject, + new String[] {"parameters", "includeRaiReason"}, + Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); } - 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[] {"language"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "language"}, + Common.getValueByPath(fromObject, new String[] {"language"})); } - 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[] {"outputMimeType"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "outputOptions", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"urlContext"}, - urlContextToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), - toObject)); + parentObject, + new String[] {"parameters", "outputOptions", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"addWatermark"}) != null) { Common.setValueByPath( - toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + parentObject, + new String[] {"parameters", "addWatermark"}, + Common.getValueByPath(fromObject, new String[] {"addWatermark"})); + } + + 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[] {"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 functionCallingConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + ObjectNode editImageParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( toObject, - new String[] {"allowedFunctionNames"}, - Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); + 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, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"instances[0]", "referenceImages"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + editImageConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode latLngToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latitude"}) != null) { + ObjectNode editImageResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"latitude"}, - Common.getValueByPath(fromObject, new String[] {"latitude"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"longitude"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"longitude"}, - Common.getValueByPath(fromObject, new String[] {"longitude"})); + 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, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode retrievalConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latLng"}) != null) { + ObjectNode embedContentConfigToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"taskType"}) != null) { Common.setValueByPath( - toObject, - new String[] {"latLng"}, - latLngToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"latLng"})), - toObject)); + parentObject, + new String[] {"requests[]", "taskType"}, + Common.getValueByPath(fromObject, new String[] {"taskType"})); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { Common.setValueByPath( - toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + 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 only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"autoTruncate"}))) { + throw new IllegalArgumentException( + "autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"documentOcr"}))) { + throw new IllegalArgumentException( + "documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audioTrackExtraction"}))) { + throw new IllegalArgumentException( + "audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode toolConfigToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionCallingConfig"}, - functionCallingConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})), - toObject)); + ObjectNode embedContentConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + JsonNode discriminatorTaskType = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"embeddingApiType"}); + String discriminatorValueTaskType = + discriminatorTaskType == null ? "PREDICT" : discriminatorTaskType.asText(); + if (discriminatorValueTaskType.equals("PREDICT")) { + if (Common.getValueByPath(fromObject, new String[] {"taskType"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"instances[]", "task_type"}, + Common.getValueByPath(fromObject, new String[] {"taskType"})); + } + } else if (discriminatorValueTaskType.equals("EMBED_CONTENT")) { + if (Common.getValueByPath(fromObject, new String[] {"taskType"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"embedContentConfig", "taskType"}, + Common.getValueByPath(fromObject, new String[] {"taskType"})); + } } - if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"retrievalConfig"}, - retrievalConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})), - toObject)); + JsonNode discriminatorTitle = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"embeddingApiType"}); + String discriminatorValueTitle = + discriminatorTitle == null ? "PREDICT" : discriminatorTitle.asText(); + if (discriminatorValueTitle.equals("PREDICT")) { + if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"instances[]", "title"}, + Common.getValueByPath(fromObject, new String[] {"title"})); + } + } else if (discriminatorValueTitle.equals("EMBED_CONTENT")) { + if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"embedContentConfig", "title"}, + Common.getValueByPath(fromObject, new String[] {"title"})); + } + } + + JsonNode discriminatorOutputDimensionality = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"embeddingApiType"}); + String discriminatorValueOutputDimensionality = + discriminatorOutputDimensionality == null + ? "PREDICT" + : discriminatorOutputDimensionality.asText(); + if (discriminatorValueOutputDimensionality.equals("PREDICT")) { + if (Common.getValueByPath(fromObject, new String[] {"outputDimensionality"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "outputDimensionality"}, + Common.getValueByPath(fromObject, new String[] {"outputDimensionality"})); + } + } else if (discriminatorValueOutputDimensionality.equals("EMBED_CONTENT")) { + if (Common.getValueByPath(fromObject, new String[] {"outputDimensionality"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"embedContentConfig", "outputDimensionality"}, + Common.getValueByPath(fromObject, new String[] {"outputDimensionality"})); + } + } + + JsonNode discriminatorMimeType = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"embeddingApiType"}); + String discriminatorValueMimeType = + discriminatorMimeType == null ? "PREDICT" : discriminatorMimeType.asText(); + if (discriminatorValueMimeType.equals("PREDICT")) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"instances[]", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); + } + } + + JsonNode discriminatorAutoTruncate = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"embeddingApiType"}); + String discriminatorValueAutoTruncate = + discriminatorAutoTruncate == null ? "PREDICT" : discriminatorAutoTruncate.asText(); + if (discriminatorValueAutoTruncate.equals("PREDICT")) { + if (Common.getValueByPath(fromObject, new String[] {"autoTruncate"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "autoTruncate"}, + Common.getValueByPath(fromObject, new String[] {"autoTruncate"})); + } + } else if (discriminatorValueAutoTruncate.equals("EMBED_CONTENT")) { + if (Common.getValueByPath(fromObject, new String[] {"autoTruncate"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"embedContentConfig", "autoTruncate"}, + Common.getValueByPath(fromObject, new String[] {"autoTruncate"})); + } + } + + JsonNode discriminatorDocumentOcr = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"embeddingApiType"}); + String discriminatorValueDocumentOcr = + discriminatorDocumentOcr == null ? "PREDICT" : discriminatorDocumentOcr.asText(); + if (discriminatorValueDocumentOcr.equals("EMBED_CONTENT")) { + if (Common.getValueByPath(fromObject, new String[] {"documentOcr"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"embedContentConfig", "documentOcr"}, + Common.getValueByPath(fromObject, new String[] {"documentOcr"})); + } + } + + JsonNode discriminatorAudioTrackExtraction = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"embeddingApiType"}); + String discriminatorValueAudioTrackExtraction = + discriminatorAudioTrackExtraction == null + ? "PREDICT" + : discriminatorAudioTrackExtraction.asText(); + if (discriminatorValueAudioTrackExtraction.equals("EMBED_CONTENT")) { + if (Common.getValueByPath(fromObject, new String[] {"audioTrackExtraction"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"embedContentConfig", "audioTrackExtraction"}, + Common.getValueByPath(fromObject, new String[] {"audioTrackExtraction"})); + } } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode prebuiltVoiceConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceName"}) != null) { + ObjectNode embedContentParametersPrivateToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"voiceName"}, - Common.getValueByPath(fromObject, new String[] {"voiceName"})); + new String[] {"requests[]", "content"}, + Transformers.tContentsForEmbed( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"content"}) != null) { + JsonNode unused = + contentToMldev( + JsonSerializable.toJsonNode( + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"content"}))), + toObject, + rootObject); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + embedContentConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } + Common.setValueByPath( + toObject, + new String[] {"requests[]", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode voiceConfigToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"}) != null) { + ObjectNode embedContentParametersPrivateToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"prebuiltVoiceConfig"}, - prebuiltVoiceConfigToMldev( - apiClient, + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + } + + JsonNode discriminatorContents = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"embeddingApiType"}); + String discriminatorValueContents = + discriminatorContents == null ? "PREDICT" : discriminatorContents.asText(); + if (discriminatorValueContents.equals("PREDICT")) { + 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"}))); + } + } + + JsonNode discriminatorContent = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"embeddingApiType"}); + String discriminatorValueContent = + discriminatorContent == null ? "PREDICT" : discriminatorContent.asText(); + if (discriminatorValueContent.equals("EMBED_CONTENT")) { + if (Common.getValueByPath(fromObject, new String[] {"content"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"content"}, + contentToVertex( + JsonSerializable.toJsonNode( + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"content"}))), + toObject, + rootObject)); + } + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + embedContentConfigToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode speakerVoiceConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"speaker"}) != null) { + ObjectNode embedContentResponseFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"embeddings"}) != null) { Common.setValueByPath( toObject, - new String[] {"speaker"}, - Common.getValueByPath(fromObject, new String[] {"speaker"})); + new String[] {"embeddings"}, + Common.getValueByPath(fromObject, new String[] {"embeddings"})); } - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode multiSpeakerVoiceConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"speakerVoiceConfigs"}) != null) { + ObjectNode embedContentResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"predictions[]", "embeddings"}) != null) { ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"speakerVoiceConfigs"}); + (ArrayNode) + Common.getValueByPath(fromObject, new String[] {"predictions[]", "embeddings"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { result.add( - speakerVoiceConfigToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + contentEmbeddingFromVertex(JsonSerializable.toJsonNode(item), toObject, rootObject)); } - Common.setValueByPath(toObject, new String[] {"speakerVoiceConfigs"}, result); + Common.setValueByPath(toObject, new String[] {"embeddings"}, result); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode speechConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); + } + + if (rootObject != null + && Common.getValueByPath(rootObject, new String[] {"embeddingApiType"}) != null + && ((JsonNode) Common.getValueByPath(rootObject, new String[] {"embeddingApiType"})) + .asText() + .equals("EMBED_CONTENT")) { + JsonNode embedding = (JsonNode) Common.getValueByPath(fromObject, new String[] {"embedding"}); + JsonNode usageMetadata = + (JsonNode) Common.getValueByPath(fromObject, new String[] {"usageMetadata"}); + JsonNode truncated = (JsonNode) Common.getValueByPath(fromObject, new String[] {"truncated"}); + if (embedding != null) { + ObjectNode stats = JsonSerializable.objectMapper.createObjectNode(); + if (usageMetadata != null && usageMetadata.get("promptTokenCount") != null) { + stats.set("token_count", usageMetadata.get("promptTokenCount")); + } + if (truncated != null) { + stats.set("truncated", truncated); + } + ((ObjectNode) embedding).set("statistics", stats); + ArrayNode embeddings = JsonSerializable.objectMapper.createArrayNode(); + embeddings.add(embedding); + Common.setValueByPath(toObject, new String[] {"embeddings"}, embeddings); + } } - if (Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode endpointFromVertex(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"endpoint"}) != null) { Common.setValueByPath( toObject, - new String[] {"multiSpeakerVoiceConfig"}, - multiSpeakerVoiceConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"})), - toObject)); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"endpoint"})); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"deployedModelId"}) != null) { Common.setValueByPath( toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + new String[] {"deployedModelId"}, + Common.getValueByPath(fromObject, new String[] {"deployedModelId"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode thinkingConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"includeThoughts"}) != null) { + ObjectNode fileDataToMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException( + "displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + 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; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { + ObjectNode functionCallToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"id"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"systemInstruction"}, - contentToMldev( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tContent( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); + 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"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"partialArgs"}))) { + throw new IllegalArgumentException( + "partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"willContinue"}))) { + throw new IllegalArgumentException( + "willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode functionCallingConfigToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"allowedFunctionNames"}, + Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mode"}, + Common.getValueByPath(fromObject, new String[] {"mode"})); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"streamFunctionCallArguments"}))) { + throw new IllegalArgumentException( + "streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent" + + " Platform mode, not in Gemini Developer API mode."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generateContentConfigToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"systemInstruction"}, + contentToMldev( + JsonSerializable.toJsonNode( + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), + toObject, + rootObject)); } if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { @@ -1081,22 +1517,26 @@ ObjectNode generateContentConfigToMldev( Common.setValueByPath( toObject, new String[] {"responseSchema"}, - schemaToMldev( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tSchema( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"responseSchema"}))), - toObject)); + Transformers.tSchema(Common.getValueByPath(fromObject, new String[] {"responseSchema"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != 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."); + throw new IllegalArgumentException( + "routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}))) { throw new IllegalArgumentException( - "modelSelectionConfig parameter is not supported in Gemini API."); + "modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); } if (Common.getValueByPath(fromObject, new String[] {"safetySettings"}) != null) { @@ -1106,7 +1546,7 @@ ObjectNode generateContentConfigToMldev( ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(safetySettingToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(safetySettingToMldev(JsonSerializable.toJsonNode(item), toObject, rootObject)); } Common.setValueByPath(parentObject, new String[] {"safetySettings"}, result); } @@ -1114,17 +1554,14 @@ ObjectNode generateContentConfigToMldev( if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { ArrayNode keyArray = (ArrayNode) - Transformers.tTools( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"tools"})); + Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { result.add( toolToMldev( - apiClient, - JsonSerializable.toJsonNode(Transformers.tTool(this.apiClient, item)), - toObject)); + JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject, rootObject)); } Common.setValueByPath(parentObject, new String[] {"tools"}, result); } @@ -1134,14 +1571,16 @@ ObjectNode generateContentConfigToMldev( parentObject, new String[] {"toolConfig"}, toolConfigToMldev( - apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"toolConfig"})), - toObject)); + toObject, + rootObject)); } if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"labels"}))) { - throw new IllegalArgumentException("labels parameter is not supported in Gemini API."); + throw new IllegalArgumentException( + "labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } if (Common.getValueByPath(fromObject, new String[] {"cachedContent"}) != null) { @@ -1170,3397 +1609,3204 @@ ObjectNode generateContentConfigToMldev( Common.setValueByPath( toObject, new String[] {"speechConfig"}, - speechConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tSpeechConfig( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"speechConfig"}))), - toObject)); + Transformers.tSpeechConfig( + Common.getValueByPath(fromObject, new String[] {"speechConfig"}))); } if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"audioTimestamp"}))) { throw new IllegalArgumentException( - "audioTimestamp parameter is not supported in Gemini API."); + "audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { Common.setValueByPath( toObject, new String[] {"thinkingConfig"}, - thinkingConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentParametersToMldev( - 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[] {"imageConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"imageConfig"}, + imageConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"imageConfig"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tContents( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + if (Common.getValueByPath(fromObject, new String[] {"enableEnhancedCivicAnswers"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"enableEnhancedCivicAnswers"}, + Common.getValueByPath(fromObject, new String[] {"enableEnhancedCivicAnswers"})); + } - for (JsonNode item : keyArray) { - result.add(contentToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"contents"}, result); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"modelArmorConfig"}))) { + throw new IllegalArgumentException( + "modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"serviceTier"}) != null) { Common.setValueByPath( - toObject, - new String[] {"generationConfig"}, - generateContentConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + parentObject, + new String[] {"serviceTier"}, + Common.getValueByPath(fromObject, new String[] {"serviceTier"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode generateContentConfigToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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"}, + contentToVertex( + JsonSerializable.toJsonNode( + Transformers.tContent( + Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), + toObject, + rootObject)); } - 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"})); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"mimeType"}))) { - throw new IllegalArgumentException("mimeType parameter is not supported in Gemini API."); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"autoTruncate"}))) { - throw new IllegalArgumentException("autoTruncate parameter is not supported in Gemini API."); + toObject, + new String[] {"topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); } - 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[] {"topK"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); } - if (Common.getValueByPath(fromObject, new String[] {"contents"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"candidateCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"requests[]", "content"}, - Transformers.tContentsForEmbed( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"}))); + new String[] {"candidateCount"}, + Common.getValueByPath(fromObject, new String[] {"candidateCount"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - embedContentConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); - } - - Common.setValueByPath( - toObject, - new String[] {"requests[]", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateImagesConfigToMldev( - ApiClient apiClient, 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."); + new String[] {"maxOutputTokens"}, + Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); } - 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[] {"stopSequences"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"stopSequences"}, + Common.getValueByPath(fromObject, new String[] {"stopSequences"})); } - if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseLogprobs"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); + toObject, + new String[] {"responseLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); } - if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"logprobs"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "aspectRatio"}, - Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); + toObject, + new String[] {"logprobs"}, + Common.getValueByPath(fromObject, new String[] {"logprobs"})); } - if (Common.getValueByPath(fromObject, new String[] {"guidanceScale"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"presencePenalty"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "guidanceScale"}, - Common.getValueByPath(fromObject, new String[] {"guidanceScale"})); + toObject, + new String[] {"presencePenalty"}, + Common.getValueByPath(fromObject, new String[] {"presencePenalty"})); } - 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[] {"frequencyPenalty"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"frequencyPenalty"}, + Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"})); } - if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "safetySetting"}, - Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); + toObject, + new String[] {"seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseMimeType"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "personGeneration"}, - Common.getValueByPath(fromObject, new String[] {"personGeneration"})); + toObject, + new String[] {"responseMimeType"}, + Common.getValueByPath(fromObject, new String[] {"responseMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseSchema"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeSafetyAttributes"}, - Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); + toObject, + new String[] {"responseSchema"}, + Transformers.tSchema(Common.getValueByPath(fromObject, new String[] {"responseSchema"}))); } - if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeRaiReason"}, - Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); + toObject, + new String[] {"responseJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); } - if (Common.getValueByPath(fromObject, new String[] {"language"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"routingConfig"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "language"}, - Common.getValueByPath(fromObject, new String[] {"language"})); + toObject, + new String[] {"routingConfig"}, + Common.getValueByPath(fromObject, new String[] {"routingConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "mimeType"}, - Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); + toObject, + new String[] {"modelConfig"}, + Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetySettings"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "outputOptions", "compressionQuality"}, - Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); + new String[] {"safetySettings"}, + Common.getValueByPath(fromObject, new String[] {"safetySettings"})); } - 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[] {"tools"}) != null) { + ArrayNode keyArray = + (ArrayNode) + Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}))) { - throw new IllegalArgumentException("enhancePrompt parameter is not supported in Gemini API."); + for (JsonNode item : keyArray) { + result.add( + toolToVertex( + JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject, rootObject)); + } + Common.setValueByPath(parentObject, new String[] {"tools"}, result); } - 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[] {"toolConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + parentObject, + new String[] {"toolConfig"}, + toolConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"toolConfig"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( - toObject, - new String[] {"instances[0]", "prompt"}, - Common.getValueByPath(fromObject, new String[] {"prompt"})); + parentObject, + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"cachedContent"}) != null) { Common.setValueByPath( - toObject, - new String[] {"config"}, - generateImagesConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + parentObject, + new String[] {"cachedContent"}, + Transformers.tCachedContentName( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"cachedContent"}))); } - return toObject; - } - - @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[] {"responseModalities"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - 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[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listModelsConfigToMldev( - 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"})); + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_query", "pageToken"}, - Common.getValueByPath(fromObject, new String[] {"pageToken"})); + toObject, + new String[] {"speechConfig"}, + Transformers.tSpeechConfig( + Common.getValueByPath(fromObject, new String[] {"speechConfig"}))); } - if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"audioTimestamp"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_query", "filter"}, - Common.getValueByPath(fromObject, new String[] {"filter"})); + toObject, + new String[] {"audioTimestamp"}, + Common.getValueByPath(fromObject, new String[] {"audioTimestamp"})); } - if (Common.getValueByPath(fromObject, new String[] {"queryBase"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_url", "models_url"}, - Transformers.tModelsUrl( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"queryBase"}))); + toObject, + new String[] {"thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } - 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[] {"imageConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - listModelsConfigToMldev( - apiClient, + new String[] {"imageConfig"}, + imageConfigToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"imageConfig"})), + toObject, + rootObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode updateModelConfigToMldev( - ApiClient apiClient, 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.isZero( + Common.getValueByPath(fromObject, new String[] {"enableEnhancedCivicAnswers"}))) { + throw new IllegalArgumentException( + "enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not" + + " in Gemini Enterprise Agent Platform mode."); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"modelArmorConfig"}) != null) { Common.setValueByPath( parentObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + new String[] {"modelArmorConfig"}, + Common.getValueByPath(fromObject, new String[] {"modelArmorConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"serviceTier"}) != null) { Common.setValueByPath( parentObject, - new String[] {"defaultCheckpointId"}, - Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); + new String[] {"serviceTier"}, + Common.getValueByPath(fromObject, new String[] {"serviceTier"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode updateModelParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode generateContentParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, + 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(contentToMldev(JsonSerializable.toJsonNode(item), toObject, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"contents"}, result); + } + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - updateModelConfigToMldev( + new String[] {"generationConfig"}, + generateContentConfigToMldev( apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + toObject, + rootObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode deleteModelParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode generateContentParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, + 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"}, - Common.getValueByPath(fromObject, new String[] {"config"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - 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[] {"contents"}) != null) { + ArrayNode keyArray = + (ArrayNode) + Transformers.tContents(Common.getValueByPath(fromObject, new String[] {"contents"})); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"tools"}))) { - throw new IllegalArgumentException("tools parameter is not supported in Gemini API."); + for (JsonNode item : keyArray) { + result.add(contentToVertex(JsonSerializable.toJsonNode(item), toObject, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"contents"}, result); } - 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[] {"config"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"generationConfig"}, + generateContentConfigToVertex( + apiClient, + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + ObjectNode generateContentResponseFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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[] {"contents"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"candidates"}) != null) { ArrayNode keyArray = - (ArrayNode) - Transformers.tContents( - this.apiClient, 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(candidateFromMldev(JsonSerializable.toJsonNode(item), toObject, rootObject)); } - Common.setValueByPath(toObject, new String[] {"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[] {"config"}, - countTokensConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"modelVersion"}, + Common.getValueByPath(fromObject, new String[] {"modelVersion"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"promptFeedback"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"promptFeedback"}, + Common.getValueByPath(fromObject, new String[] {"promptFeedback"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode imageToMldev(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[] {"responseId"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseId"}, + Common.getValueByPath(fromObject, new String[] {"responseId"})); } - if (Common.getValueByPath(fromObject, new String[] {"imageBytes"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"bytesBase64Encoded"}, - Transformers.tBytes( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"imageBytes"}))); + new String[] {"usageMetadata"}, + Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"modelStatus"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"modelStatus"}, + Common.getValueByPath(fromObject, new String[] {"modelStatus"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"numberOfVideos"}) != null) { + ObjectNode generateContentResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfVideos"})); - } - - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}))) { - throw new IllegalArgumentException("outputGcsUri parameter is not supported in Gemini API."); + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - 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[] {"candidates"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"candidates"}, + Common.getValueByPath(fromObject, new String[] {"candidates"})); } - if (Common.getValueByPath(fromObject, new String[] {"durationSeconds"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "durationSeconds"}, - Common.getValueByPath(fromObject, new String[] {"durationSeconds"})); + toObject, + new String[] {"createTime"}, + Common.getValueByPath(fromObject, new String[] {"createTime"})); } - 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[] {"modelVersion"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"modelVersion"}, + Common.getValueByPath(fromObject, new String[] {"modelVersion"})); } - if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"promptFeedback"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "aspectRatio"}, - Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); + toObject, + new String[] {"promptFeedback"}, + Common.getValueByPath(fromObject, new String[] {"promptFeedback"})); } - 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[] {"responseId"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseId"}, + Common.getValueByPath(fromObject, new String[] {"responseId"})); } - if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "personGeneration"}, - Common.getValueByPath(fromObject, new String[] {"personGeneration"})); + toObject, + new String[] {"usageMetadata"}, + Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"pubsubTopic"}))) { - throw new IllegalArgumentException("pubsubTopic parameter is not supported in Gemini API."); + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generateImagesConfigToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}))) { + throw new IllegalArgumentException( + "outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"negativePrompt"}))) { + throw new IllegalArgumentException( + "negativePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "negativePrompt"}, - Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); } - if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "enhancePrompt"}, - Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); + new String[] {"parameters", "aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"generateAudio"}))) { - throw new IllegalArgumentException("generateAudio 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"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"seed"}))) { + throw new IllegalArgumentException( + "seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosParametersToMldev( - 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[] {"safetyFilterLevel"}) != null) { + safetyFilterLevelMldevEnumValidate( + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); Common.setValueByPath( - toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + parentObject, + new String[] {"parameters", "safetySetting"}, + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); } - if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { + personGenerationMldevEnumValidate( + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); Common.setValueByPath( - toObject, - new String[] {"instances[0]", "prompt"}, - Common.getValueByPath(fromObject, new String[] {"prompt"})); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { Common.setValueByPath( - toObject, - new String[] {"instances[0]", "image"}, - imageToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"image"})), - toObject)); + parentObject, + new String[] {"parameters", "includeSafetyAttributes"}, + Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { Common.setValueByPath( - toObject, - new String[] {"config"}, - generateVideosConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + parentObject, + new String[] {"parameters", "includeRaiReason"}, + Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"language"}) != null) { Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + parentObject, + new String[] {"parameters", "language"}, + Common.getValueByPath(fromObject, new String[] {"language"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { Common.setValueByPath( - toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + parentObject, + new String[] {"parameters", "outputOptions", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + parentObject, + new String[] {"parameters", "outputOptions", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"addWatermark"}))) { + throw new IllegalArgumentException( + "addWatermark parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode blobToVertex(ApiClient apiClient, 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.isZero(Common.getValueByPath(fromObject, new String[] {"labels"}))) { + throw new IllegalArgumentException( + "labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"imageSize"}) != null) { Common.setValueByPath( - toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + parentObject, + new String[] {"parameters", "sampleImageSize"}, + Common.getValueByPath(fromObject, new String[] {"imageSize"})); } - 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[] {"enhancePrompt"}))) { + throw new IllegalArgumentException( + "enhancePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToVertex(ApiClient apiClient, 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"})); - } + ObjectNode generateImagesConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { Common.setValueByPath( - toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + parentObject, + new String[] {"parameters", "storageUri"}, + Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + parentObject, + new String[] {"parameters", "negativePrompt"}, + Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode partToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( - toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + parentObject, + new String[] {"parameters", "aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"guidanceScale"}) != null) { Common.setValueByPath( - toObject, - new String[] {"inlineData"}, - blobToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + parentObject, + new String[] {"parameters", "guidanceScale"}, + Common.getValueByPath(fromObject, new String[] {"guidanceScale"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + parentObject, + new String[] {"parameters", "seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { Common.setValueByPath( - toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + parentObject, + new String[] {"parameters", "safetySetting"}, + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { Common.setValueByPath( - toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { Common.setValueByPath( - toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + parentObject, + new String[] {"parameters", "includeSafetyAttributes"}, + Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + parentObject, + new String[] {"parameters", "includeRaiReason"}, + Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"language"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + parentObject, + new String[] {"parameters", "language"}, + Common.getValueByPath(fromObject, new String[] {"language"})); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + parentObject, + new String[] {"parameters", "outputOptions", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "outputOptions", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode contentToVertex(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[] {"addWatermark"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "addWatermark"}, + Common.getValueByPath(fromObject, new String[] {"addWatermark"})); + } - for (JsonNode item : keyArray) { - result.add(partToVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); + 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[] {"role"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"imageSize"}) != null) { Common.setValueByPath( - toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + 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 schemaToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"anyOf"}) != null) { + ObjectNode generateImagesParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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[] {"prompt"}) != null) { Common.setValueByPath( toObject, - new String[] {"default"}, - Common.getValueByPath(fromObject, new String[] {"default"})); + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - 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[] {"config"}) != null) { + JsonNode unused = + generateImagesConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } - if (Common.getValueByPath(fromObject, new String[] {"enum"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"enum"}, - Common.getValueByPath(fromObject, new String[] {"enum"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"example"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode generateImagesParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"example"}, - Common.getValueByPath(fromObject, new String[] {"example"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"format"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( toObject, - new String[] {"format"}, - Common.getValueByPath(fromObject, new String[] {"format"})); + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - 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[] {"config"}) != null) { + JsonNode unused = + generateImagesConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } - if (Common.getValueByPath(fromObject, new String[] {"maxItems"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"maxItems"}, - Common.getValueByPath(fromObject, new String[] {"maxItems"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"maxLength"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode generateImagesResponseFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"maxLength"}, - Common.getValueByPath(fromObject, new String[] {"maxLength"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"maxProperties"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"maxProperties"}, - Common.getValueByPath(fromObject, new String[] {"maxProperties"})); + 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, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"maximum"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"positivePromptSafetyAttributes"}) + != null) { Common.setValueByPath( toObject, - new String[] {"maximum"}, - Common.getValueByPath(fromObject, new String[] {"maximum"})); + new String[] {"positivePromptSafetyAttributes"}, + safetyAttributesFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath( + fromObject, new String[] {"positivePromptSafetyAttributes"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"minItems"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generateImagesResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"minItems"}, - Common.getValueByPath(fromObject, new String[] {"minItems"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"minLength"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"minLength"}, - Common.getValueByPath(fromObject, new String[] {"minLength"})); + 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, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"minProperties"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"positivePromptSafetyAttributes"}) + != null) { Common.setValueByPath( toObject, - new String[] {"minProperties"}, - Common.getValueByPath(fromObject, new String[] {"minProperties"})); + new String[] {"positivePromptSafetyAttributes"}, + safetyAttributesFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath( + fromObject, new String[] {"positivePromptSafetyAttributes"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"minimum"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generateVideosConfigToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"numberOfVideos"}) != null) { Common.setValueByPath( - toObject, - new String[] {"minimum"}, - Common.getValueByPath(fromObject, new String[] {"minimum"})); + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfVideos"})); } - if (Common.getValueByPath(fromObject, new String[] {"nullable"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"nullable"}, - Common.getValueByPath(fromObject, new String[] {"nullable"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}))) { + throw new IllegalArgumentException( + "outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } - 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[] {"fps"}))) { + throw new IllegalArgumentException( + "fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"properties"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"durationSeconds"}) != null) { Common.setValueByPath( - toObject, - new String[] {"properties"}, - Common.getValueByPath(fromObject, new String[] {"properties"})); + parentObject, + new String[] {"parameters", "durationSeconds"}, + Common.getValueByPath(fromObject, new String[] {"durationSeconds"})); } - if (Common.getValueByPath(fromObject, new String[] {"propertyOrdering"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"propertyOrdering"}, - Common.getValueByPath(fromObject, new String[] {"propertyOrdering"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"seed"}))) { + throw new IllegalArgumentException( + "seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"required"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( - toObject, - new String[] {"required"}, - Common.getValueByPath(fromObject, new String[] {"required"})); + parentObject, + new String[] {"parameters", "aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"resolution"}) != null) { Common.setValueByPath( - toObject, - new String[] {"title"}, - Common.getValueByPath(fromObject, new String[] {"title"})); + parentObject, + new String[] {"parameters", "resolution"}, + Common.getValueByPath(fromObject, new String[] {"resolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"type"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { Common.setValueByPath( - toObject, - new String[] {"type"}, - Common.getValueByPath(fromObject, new String[] {"type"})); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"pubsubTopic"}))) { + throw new IllegalArgumentException( + "pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode modelSelectionConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"featureSelectionPreference"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"featureSelectionPreference"}, - Common.getValueByPath(fromObject, new String[] {"featureSelectionPreference"})); + parentObject, + new String[] {"parameters", "negativePrompt"}, + Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode safetySettingToVertex( - 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[] {"enhancePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"method"}, - Common.getValueByPath(fromObject, new String[] {"method"})); + parentObject, + new String[] {"parameters", "enhancePrompt"}, + Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"category"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"category"}, - Common.getValueByPath(fromObject, new String[] {"category"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"generateAudio"}))) { + throw new IllegalArgumentException( + "generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"threshold"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"lastFrame"}) != null) { Common.setValueByPath( - toObject, - new String[] {"threshold"}, - Common.getValueByPath(fromObject, new String[] {"threshold"})); + parentObject, + new String[] {"instances[0]", "lastFrame"}, + imageToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"lastFrame"})), + toObject, + rootObject)); } - 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 functionDeclarationToVertex( - 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."); + for (JsonNode item : keyArray) { + result.add( + videoGenerationReferenceImageToMldev( + JsonSerializable.toJsonNode(item), toObject, rootObject)); + } + Common.setValueByPath(parentObject, new String[] {"instances[0]", "referenceImages"}, result); } - 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[] {"mask"}))) { + throw new IllegalArgumentException( + "mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); } - 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[] {"compressionQuality"}))) { + throw new IllegalArgumentException( + "compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"parameters"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"parameters"}, - Common.getValueByPath(fromObject, new String[] {"parameters"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"labels"}))) { + throw new IllegalArgumentException( + "labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"webhookConfig"}) != null) { Common.setValueByPath( - toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); + parentObject, + new String[] {"webhookConfig"}, + Common.getValueByPath(fromObject, new String[] {"webhookConfig"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"resizeMode"}))) { + throw new IllegalArgumentException( + "resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"startTime"}) != null) { + ObjectNode generateVideosConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"numberOfVideos"}) != null) { Common.setValueByPath( - toObject, - new String[] {"startTime"}, - Common.getValueByPath(fromObject, new String[] {"startTime"})); + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfVideos"})); } - if (Common.getValueByPath(fromObject, new String[] {"endTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { Common.setValueByPath( - toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); + parentObject, + new String[] {"parameters", "storageUri"}, + Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"timeRangeFilter"}, - intervalToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToVertex( - 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[] {"fps"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + parentObject, + new String[] {"parameters", "fps"}, + Common.getValueByPath(fromObject, new String[] {"fps"})); } - if (Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"durationSeconds"}) != null) { Common.setValueByPath( - toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); + parentObject, + new String[] {"parameters", "durationSeconds"}, + Common.getValueByPath(fromObject, new String[] {"durationSeconds"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( - toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), - toObject)); + parentObject, + new String[] {"parameters", "seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode enterpriseWebSearchToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode apiKeyConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyString"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( - toObject, - new String[] {"apiKeyString"}, - Common.getValueByPath(fromObject, new String[] {"apiKeyString"})); + parentObject, + new String[] {"parameters", "aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode authConfigToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"resolution"}) != null) { Common.setValueByPath( - toObject, - new String[] {"apiKeyConfig"}, - apiKeyConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"})), - toObject)); + parentObject, + new String[] {"parameters", "resolution"}, + Common.getValueByPath(fromObject, new String[] {"resolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"authType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { Common.setValueByPath( - toObject, - new String[] {"authType"}, - Common.getValueByPath(fromObject, new String[] {"authType"})); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pubsubTopic"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleServiceAccountConfig"}, - Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"})); + parentObject, + new String[] {"parameters", "pubsubTopic"}, + Common.getValueByPath(fromObject, new String[] {"pubsubTopic"})); } - if (Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"httpBasicAuthConfig"}, - Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"})); + parentObject, + new String[] {"parameters", "negativePrompt"}, + Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"oauthConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"oauthConfig"}, - Common.getValueByPath(fromObject, new String[] {"oauthConfig"})); + parentObject, + new String[] {"parameters", "enhancePrompt"}, + Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"oidcConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"generateAudio"}) != null) { Common.setValueByPath( - toObject, - new String[] {"oidcConfig"}, - Common.getValueByPath(fromObject, new String[] {"oidcConfig"})); + parentObject, + new String[] {"parameters", "generateAudio"}, + Common.getValueByPath(fromObject, new String[] {"generateAudio"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleMapsToVertex(ApiClient apiClient, 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( - apiClient, + parentObject, + new String[] {"instances[0]", "lastFrame"}, + imageToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"authConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"lastFrame"})), + toObject, + rootObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"referenceImages"}) != null) { ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}); + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"referenceImages"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { result.add( - functionDeclarationToVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); + videoGenerationReferenceImageToVertex( + JsonSerializable.toJsonNode(item), toObject, rootObject)); } - Common.setValueByPath(toObject, new String[] {"functionDeclarations"}, result); + Common.setValueByPath(parentObject, new String[] {"instances[0]", "referenceImages"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"retrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mask"}) != null) { Common.setValueByPath( - toObject, - new String[] {"retrieval"}, - Common.getValueByPath(fromObject, new String[] {"retrieval"})); + parentObject, + new String[] {"instances[0]", "mask"}, + videoGenerationMaskToVertex( + JsonSerializable.toJsonNode(Common.getValueByPath(fromObject, new String[] {"mask"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"compressionQuality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleSearch"}, - googleSearchToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); + parentObject, + new String[] {"parameters", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"compressionQuality"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( - toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - toObject)); + parentObject, + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); } - if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"webhookConfig"}))) { + throw new IllegalArgumentException( + "webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"resizeMode"}) != null) { Common.setValueByPath( - toObject, - new String[] {"enterpriseWebSearch"}, - enterpriseWebSearchToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})), - toObject)); + parentObject, + new String[] {"parameters", "resizeMode"}, + Common.getValueByPath(fromObject, new String[] {"resizeMode"})); } - if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generateVideosOperationFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"googleMaps"}, - googleMapsToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleMaps"})), - toObject)); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlContext"}, - urlContextToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContext"})), - toObject)); + new String[] {"metadata"}, + Common.getValueByPath(fromObject, new String[] {"metadata"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { Common.setValueByPath( toObject, - new String[] {"codeExecution"}, - Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + new String[] {"done"}, + Common.getValueByPath(fromObject, new String[] {"done"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionCallingConfigToVertex( - 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[] {"error"}) != null) { Common.setValueByPath( toObject, - new String[] {"mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); } - if (Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"response", "generateVideoResponse"}) + != null) { Common.setValueByPath( toObject, - new String[] {"allowedFunctionNames"}, - Common.getValueByPath(fromObject, new String[] {"allowedFunctionNames"})); + new String[] {"response"}, + generateVideosResponseFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath( + fromObject, new String[] {"response", "generateVideoResponse"})), + toObject, + rootObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode latLngToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latitude"}) != null) { + ObjectNode generateVideosOperationFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"latitude"}, - Common.getValueByPath(fromObject, new String[] {"latitude"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"longitude"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"longitude"}, - Common.getValueByPath(fromObject, new String[] {"longitude"})); + 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 retrievalConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"latLng"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { Common.setValueByPath( toObject, - new String[] {"latLng"}, - latLngToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"latLng"})), - toObject)); + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { Common.setValueByPath( toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + new String[] {"response"}, + generateVideosResponseFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"response"})), + toObject, + rootObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode toolConfigToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { + ObjectNode generateVideosParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"functionCallingConfig"}, - functionCallingConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})), - toObject)); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( toObject, - new String[] {"retrievalConfig"}, - retrievalConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})), - toObject)); + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode prebuiltVoiceConfigToVertex( - 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[] {"image"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceName"}, - Common.getValueByPath(fromObject, new String[] {"voiceName"})); + new String[] {"instances[0]", "image"}, + imageToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject, + rootObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode voiceConfigToVertex( - 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[] {"video"}) != null) { Common.setValueByPath( toObject, - new String[] {"prebuiltVoiceConfig"}, - prebuiltVoiceConfigToVertex( - apiClient, + new String[] {"instances[0]", "video"}, + videoToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject, + rootObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode speakerVoiceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"speaker"}))) { - throw new IllegalArgumentException("speaker parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"source"}) != null) { + JsonNode unused = + generateVideosSourceToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"source"})), + toObject, + rootObject); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"voiceConfig"}))) { - throw new IllegalArgumentException("voiceConfig parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + generateVideosConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode multiSpeakerVoiceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"speakerVoiceConfigs"}))) { - throw new IllegalArgumentException( - "speakerVoiceConfigs parameter is not supported in Vertex AI."); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode speechConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { + ObjectNode generateVideosParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceConfig"}, - voiceConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - 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[] {"prompt"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); + } + + 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, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + new String[] {"instances[0]", "video"}, + videoToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject, + rootObject)); + } + + if (Common.getValueByPath(fromObject, new String[] {"source"}) != null) { + JsonNode unused = + generateVideosSourceToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"source"})), + toObject, + rootObject); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + generateVideosConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode thinkingConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"includeThoughts"}) != null) { + ObjectNode generateVideosResponseFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"includeThoughts"}, - Common.getValueByPath(fromObject, new String[] {"includeThoughts"})); + new String[] {"raiMediaFilteredCount"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); } - if (Common.getValueByPath(fromObject, new String[] {"thinkingBudget"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { Common.setValueByPath( toObject, - new String[] {"thinkingBudget"}, - Common.getValueByPath(fromObject, new String[] {"thinkingBudget"})); + new String[] {"raiMediaFilteredReasons"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode generateVideosResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"systemInstruction"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"systemInstruction"}, - contentToVertex( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tContent( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); + for (JsonNode item : keyArray) { + result.add( + generatedVideoFromVertex(JsonSerializable.toJsonNode(item), toObject, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { Common.setValueByPath( toObject, - new String[] {"temperature"}, - Common.getValueByPath(fromObject, new String[] {"temperature"})); + new String[] {"raiMediaFilteredCount"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); } - if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { Common.setValueByPath( toObject, - new String[] {"topP"}, - Common.getValueByPath(fromObject, new String[] {"topP"})); + new String[] {"raiMediaFilteredReasons"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); } - if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"topK"}, - Common.getValueByPath(fromObject, new String[] {"topK"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"candidateCount"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode generateVideosSourceToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"candidateCount"}, - Common.getValueByPath(fromObject, new String[] {"candidateCount"})); + parentObject, + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( - toObject, - new String[] {"maxOutputTokens"}, - Common.getValueByPath(fromObject, new String[] {"maxOutputTokens"})); + parentObject, + new String[] {"instances[0]", "image"}, + imageToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"stopSequences"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( - toObject, - new String[] {"stopSequences"}, - Common.getValueByPath(fromObject, new String[] {"stopSequences"})); + parentObject, + new String[] {"instances[0]", "video"}, + videoToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"responseLogprobs"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generateVideosSourceToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"responseLogprobs"}, - Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); + parentObject, + new String[] {"instances[0]", "prompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"logprobs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( - toObject, - new String[] {"logprobs"}, - Common.getValueByPath(fromObject, new String[] {"logprobs"})); + parentObject, + new String[] {"instances[0]", "image"}, + imageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"presencePenalty"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( - toObject, - new String[] {"presencePenalty"}, - Common.getValueByPath(fromObject, new String[] {"presencePenalty"})); + parentObject, + new String[] {"instances[0]", "video"}, + videoToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generatedImageFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"frequencyPenalty"}, - Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"})); + new String[] {"image"}, + imageFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"}) != null) { Common.setValueByPath( toObject, - new String[] {"seed"}, - Common.getValueByPath(fromObject, new String[] {"seed"})); + new String[] {"raiFilteredReason"}, + Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"})); } - if (Common.getValueByPath(fromObject, new String[] {"responseMimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseMimeType"}, - Common.getValueByPath(fromObject, new String[] {"responseMimeType"})); + new String[] {"safetyAttributes"}, + safetyAttributesFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"responseSchema"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generatedImageFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseSchema"}, - schemaToVertex( - apiClient, + new String[] {"image"}, + imageFromVertex( JsonSerializable.toJsonNode( - Transformers.tSchema( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"responseSchema"}))), - toObject)); + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"routingConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"}) != null) { Common.setValueByPath( toObject, - new String[] {"routingConfig"}, - Common.getValueByPath(fromObject, new String[] {"routingConfig"})); + new String[] {"raiFilteredReason"}, + Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"})); } - if (Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"modelConfig"}, - modelSelectionConfigToVertex( - apiClient, + new String[] {"safetyAttributes"}, + safetyAttributesFromVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject, + rootObject)); } - 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"safetySettings"}, result); + if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"enhancedPrompt"}, + Common.getValueByPath(fromObject, new String[] {"prompt"})); } - if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tTools( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"tools"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add( - toolToVertex( - apiClient, - JsonSerializable.toJsonNode(Transformers.tTool(this.apiClient, item)), - toObject)); - } - Common.setValueByPath(parentObject, new String[] {"tools"}, result); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"toolConfig"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode generatedImageMaskFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"toolConfig"}, - toolConfigToVertex( - apiClient, + toObject, + new String[] {"mask"}, + imageFromVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"toolConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject, + rootObject)); } if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( - parentObject, + toObject, 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"}))); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode generatedVideoFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( toObject, - new String[] {"responseModalities"}, - Common.getValueByPath(fromObject, new String[] {"responseModalities"})); + new String[] {"video"}, + videoFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject, + rootObject)); } - 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( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tSpeechConfig( - this.apiClient, - 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"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode generatedVideoFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"thinkingConfig"}, - thinkingConfigToVertex( - apiClient, + new String[] {"video"}, + videoFromVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject, + rootObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + ObjectNode generationConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"}) != 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( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(contentToVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"contents"}, result); + new String[] {"modelConfig"}, + Common.getValueByPath(fromObject, new String[] {"modelSelectionConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"}) != null) { Common.setValueByPath( toObject, - new String[] {"generationConfig"}, - generateContentConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"responseJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentConfigToVertex( - 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[] {"audioTimestamp"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"instances[]", "task_type"}, - Common.getValueByPath(fromObject, new String[] {"taskType"})); + toObject, + new String[] {"audioTimestamp"}, + Common.getValueByPath(fromObject, new String[] {"audioTimestamp"})); } - if (Common.getValueByPath(fromObject, new String[] {"title"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"candidateCount"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"instances[]", "title"}, - Common.getValueByPath(fromObject, new String[] {"title"})); + toObject, + new String[] {"candidateCount"}, + Common.getValueByPath(fromObject, new String[] {"candidateCount"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputDimensionality"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputDimensionality"}, - Common.getValueByPath(fromObject, new String[] {"outputDimensionality"})); + toObject, + new String[] {"enableAffectiveDialog"}, + Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"instances[]", "mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + toObject, + new String[] {"frequencyPenalty"}, + Common.getValueByPath(fromObject, new String[] {"frequencyPenalty"})); } - if (Common.getValueByPath(fromObject, new String[] {"autoTruncate"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"logprobs"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "autoTruncate"}, - Common.getValueByPath(fromObject, new String[] {"autoTruncate"})); + toObject, + new String[] {"logprobs"}, + Common.getValueByPath(fromObject, new String[] {"logprobs"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentParametersToVertex( - 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[] {"mediaResolution"}) != null) { Common.setValueByPath( toObject, - new String[] {"instances[]", "content"}, - Transformers.tContentsForEmbed( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"}))); + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"presencePenalty"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - embedContentConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"presencePenalty"}, + Common.getValueByPath(fromObject, new String[] {"presencePenalty"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateImagesConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseLogprobs"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "storageUri"}, - Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); + toObject, + new String[] {"responseLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); } - if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseMimeType"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "negativePrompt"}, - Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); + toObject, + new String[] {"responseMimeType"}, + Common.getValueByPath(fromObject, new String[] {"responseMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); + toObject, + new String[] {"responseModalities"}, + Common.getValueByPath(fromObject, new String[] {"responseModalities"})); } - if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"responseSchema"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "aspectRatio"}, - Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); + toObject, + new String[] {"responseSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseSchema"})); } - if (Common.getValueByPath(fromObject, new String[] {"guidanceScale"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"routingConfig"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "guidanceScale"}, - Common.getValueByPath(fromObject, new String[] {"guidanceScale"})); + toObject, + new String[] {"routingConfig"}, + Common.getValueByPath(fromObject, new String[] {"routingConfig"})); } if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "seed"}, + toObject, + new String[] {"seed"}, Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"speechConfig"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "safetySetting"}, - Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); + toObject, + new String[] {"speechConfig"}, + Common.getValueByPath(fromObject, new String[] {"speechConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"stopSequences"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "personGeneration"}, - Common.getValueByPath(fromObject, new String[] {"personGeneration"})); + toObject, + new String[] {"stopSequences"}, + Common.getValueByPath(fromObject, new String[] {"stopSequences"})); } - if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"temperature"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeSafetyAttributes"}, - Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); + toObject, + new String[] {"temperature"}, + Common.getValueByPath(fromObject, new String[] {"temperature"})); } - if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeRaiReason"}, - Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); + toObject, + new String[] {"thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"language"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "language"}, - Common.getValueByPath(fromObject, new String[] {"language"})); + toObject, + new String[] {"topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "mimeType"}, - Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); + toObject, + new String[] {"topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "compressionQuality"}, - Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"enableEnhancedCivicAnswers"}))) { + throw new IllegalArgumentException( + "enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not" + + " in Gemini Enterprise Agent Platform mode."); } - if (Common.getValueByPath(fromObject, new String[] {"addWatermark"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "addWatermark"}, - Common.getValueByPath(fromObject, new String[] {"addWatermark"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode getModelParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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", "name"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateImagesParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode getModelParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "model"}, + new String[] {"_url", "name"}, Transformers.tModel( this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode googleMapsToMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"authConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"instances[0]", "prompt"}, - Common.getValueByPath(fromObject, new String[] {"prompt"})); + new String[] {"authConfig"}, + authConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"authConfig"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enableWidget"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - generateImagesConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"enableWidget"}, + Common.getValueByPath(fromObject, new String[] {"enableWidget"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode imageToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + ObjectNode googleSearchToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"searchTypes"}) != null) { Common.setValueByPath( toObject, - new String[] {"gcsUri"}, - Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + new String[] {"searchTypes"}, + Common.getValueByPath(fromObject, new String[] {"searchTypes"})); } - if (Common.getValueByPath(fromObject, new String[] {"imageBytes"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"bytesBase64Encoded"}, - Transformers.tBytes( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"imageBytes"}))); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"blockingConfidence"}))) { + throw new IllegalArgumentException( + "blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"excludeDomains"}))) { + throw new IllegalArgumentException( + "excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"timeRangeFilter"}, + Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode maskReferenceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"maskMode"}) != null) { + ObjectNode imageConfigToMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( toObject, - new String[] {"maskMode"}, - Common.getValueByPath(fromObject, new String[] {"maskMode"})); + new String[] {"aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - if (Common.getValueByPath(fromObject, new String[] {"segmentationClasses"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"imageSize"}) != null) { Common.setValueByPath( toObject, - new String[] {"maskClasses"}, - Common.getValueByPath(fromObject, new String[] {"segmentationClasses"})); + new String[] {"imageSize"}, + Common.getValueByPath(fromObject, new String[] {"imageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"maskDilation"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"dilation"}, - Common.getValueByPath(fromObject, new String[] {"maskDilation"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"personGeneration"}))) { + throw new IllegalArgumentException( + "personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"prominentPeople"}))) { + throw new IllegalArgumentException( + "prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"outputMimeType"}))) { + throw new IllegalArgumentException( + "outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}))) { + throw new IllegalArgumentException( + "outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"imageOutputOptions"}))) { + throw new IllegalArgumentException( + "imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode controlReferenceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"controlType"}) != null) { + ObjectNode imageConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { Common.setValueByPath( toObject, - new String[] {"controlType"}, - Common.getValueByPath(fromObject, new String[] {"controlType"})); + new String[] {"aspectRatio"}, + Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); } - if (Common.getValueByPath(fromObject, new String[] {"enableControlImageComputation"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"imageSize"}) != null) { Common.setValueByPath( toObject, - new String[] {"computeControl"}, - Common.getValueByPath(fromObject, new String[] {"enableControlImageComputation"})); + new String[] {"imageSize"}, + Common.getValueByPath(fromObject, new String[] {"imageSize"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode styleReferenceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"styleDescription"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"prominentPeople"}) != null) { Common.setValueByPath( toObject, - new String[] {"styleDescription"}, - Common.getValueByPath(fromObject, new String[] {"styleDescription"})); + new String[] {"prominentPeople"}, + Common.getValueByPath(fromObject, new String[] {"prominentPeople"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"imageOutputOptions", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode subjectReferenceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"subjectType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { Common.setValueByPath( toObject, - new String[] {"subjectType"}, - Common.getValueByPath(fromObject, new String[] {"subjectType"})); + new String[] {"imageOutputOptions", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); } - if (Common.getValueByPath(fromObject, new String[] {"subjectDescription"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"imageOutputOptions"}) != null) { Common.setValueByPath( toObject, - new String[] {"subjectDescription"}, - Common.getValueByPath(fromObject, new String[] {"subjectDescription"})); + new String[] {"imageOutputOptions"}, + Common.getValueByPath(fromObject, new String[] {"imageOutputOptions"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode referenceImageAPIToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"referenceImage"}) != null) { + ObjectNode imageFromMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}) != null) { Common.setValueByPath( toObject, - new String[] {"referenceImage"}, - imageToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"referenceImage"})), - toObject)); + new String[] {"imageBytes"}, + Transformers.tBytes( + Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}))); } - if (Common.getValueByPath(fromObject, new String[] {"referenceId"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"referenceId"}, - Common.getValueByPath(fromObject, new String[] {"referenceId"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"referenceType"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode imageFromVertex(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"referenceType"}, - Common.getValueByPath(fromObject, new String[] {"referenceType"})); + new String[] {"gcsUri"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"maskImageConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}) != null) { Common.setValueByPath( toObject, - new String[] {"maskImageConfig"}, - maskReferenceConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"maskImageConfig"})), - toObject)); + new String[] {"imageBytes"}, + Transformers.tBytes( + Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}))); } - if (Common.getValueByPath(fromObject, new String[] {"controlImageConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"controlImageConfig"}, - controlReferenceConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"controlImageConfig"})), - toObject)); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"styleImageConfig"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode imageToMldev(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 only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"imageBytes"}) != null) { Common.setValueByPath( toObject, - new String[] {"styleImageConfig"}, - styleReferenceConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"styleImageConfig"})), - toObject)); + new String[] {"bytesBase64Encoded"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"imageBytes"}))); } - if (Common.getValueByPath(fromObject, new String[] {"subjectImageConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"subjectImageConfig"}, - subjectReferenceConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"subjectImageConfig"})), - toObject)); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode editImageConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { + ObjectNode imageToVertex(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "storageUri"}, - Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); + toObject, + new String[] {"gcsUri"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"imageBytes"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "negativePrompt"}, - Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); + toObject, + new String[] {"bytesBase64Encoded"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"imageBytes"}))); } - if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); + toObject, + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "aspectRatio"}, - Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"guidanceScale"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "guidanceScale"}, - Common.getValueByPath(fromObject, new String[] {"guidanceScale"})); - } + @ExcludeFromGeneratedCoverageReport + ObjectNode listModelsConfigToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "seed"}, - Common.getValueByPath(fromObject, new String[] {"seed"})); + new String[] {"_query", "pageSize"}, + Common.getValueByPath(fromObject, new String[] {"pageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "safetySetting"}, - Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "personGeneration"}, - Common.getValueByPath(fromObject, new String[] {"personGeneration"})); + new String[] {"_query", "filter"}, + Common.getValueByPath(fromObject, new String[] {"filter"})); } - if (Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"queryBase"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "includeSafetyAttributes"}, - Common.getValueByPath(fromObject, new String[] {"includeSafetyAttributes"})); + new String[] {"_url", "models_url"}, + Transformers.tModelsUrl( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"queryBase"}))); } - if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeRaiReason"}, - Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"language"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"parameters", "language"}, - Common.getValueByPath(fromObject, new String[] {"language"})); - } + @ExcludeFromGeneratedCoverageReport + ObjectNode listModelsConfigToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "outputOptions", "mimeType"}, - Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); + new String[] {"_query", "pageSize"}, + Common.getValueByPath(fromObject, new String[] {"pageSize"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"pageToken"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "outputOptions", "compressionQuality"}, - Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); + new String[] {"_query", "pageToken"}, + Common.getValueByPath(fromObject, new String[] {"pageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"editMode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"filter"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "editMode"}, - Common.getValueByPath(fromObject, new String[] {"editMode"})); + new String[] {"_query", "filter"}, + Common.getValueByPath(fromObject, new String[] {"filter"})); } - if (Common.getValueByPath(fromObject, new String[] {"baseSteps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"queryBase"}) != null) { Common.setValueByPath( parentObject, - new String[] {"parameters", "editConfig", "baseSteps"}, - Common.getValueByPath(fromObject, new String[] {"baseSteps"})); + new String[] {"_url", "models_url"}, + Transformers.tModelsUrl( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"queryBase"}))); } 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"}))); + ObjectNode listModelsParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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, + rootObject); } - if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listModelsParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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, + rootObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode listModelsResponseFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"instances[0]", "prompt"}, - Common.getValueByPath(fromObject, new String[] {"prompt"})); + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"referenceImages"}) != 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[] {"_self"}) != null) { ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"referenceImages"}); + (ArrayNode) + Transformers.tExtractModels( + Common.getValueByPath(fromObject, new String[] {"_self"})); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add( - referenceImageAPIToVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(modelFromMldev(JsonSerializable.toJsonNode(item), toObject, rootObject)); } - Common.setValueByPath(toObject, new String[] {"instances[0]", "referenceImages"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"config"}, - editImageConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + Common.setValueByPath(toObject, new String[] {"models"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode upscaleImageAPIConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { + ObjectNode listModelsResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "includeRaiReason"}, - Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); + toObject, + new String[] {"sdkHttpResponse"}, + Common.getValueByPath(fromObject, new String[] {"sdkHttpResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "mimeType"}, - Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); + toObject, + new String[] {"nextPageToken"}, + Common.getValueByPath(fromObject, new String[] {"nextPageToken"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { + 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, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"models"}, result); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode maskReferenceConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"maskMode"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "outputOptions", "compressionQuality"}, - Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); + toObject, + new String[] {"maskMode"}, + Common.getValueByPath(fromObject, new String[] {"maskMode"})); } - if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"segmentationClasses"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); + toObject, + new String[] {"maskClasses"}, + Common.getValueByPath(fromObject, new String[] {"segmentationClasses"})); } - if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maskDilation"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "mode"}, - Common.getValueByPath(fromObject, new String[] {"mode"})); + toObject, + new String[] {"dilation"}, + Common.getValueByPath(fromObject, new String[] {"maskDilation"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode upscaleImageAPIParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + ObjectNode modelFromMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { Common.setValueByPath( toObject, - new String[] {"instances[0]", "image"}, - imageToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"image"})), - toObject)); + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"displayName"})); } - if (Common.getValueByPath(fromObject, new String[] {"upscaleFactor"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( toObject, - new String[] {"parameters", "upscaleConfig", "upscaleFactor"}, - Common.getValueByPath(fromObject, new String[] {"upscaleFactor"})); + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"version"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - upscaleImageAPIConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"version"}, + Common.getValueByPath(fromObject, new String[] {"version"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode getModelParametersToVertex( - 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[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"tunedModelInfo"}, + Common.getValueByPath(fromObject, new String[] {"_self"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inputTokenLimit"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"inputTokenLimit"}, + Common.getValueByPath(fromObject, new String[] {"inputTokenLimit"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode listModelsConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"outputTokenLimit"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"outputTokenLimit"}, + Common.getValueByPath(fromObject, new String[] {"outputTokenLimit"})); + } - if (Common.getValueByPath(fromObject, new String[] {"pageSize"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"supportedGenerationMethods"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_query", "pageSize"}, - Common.getValueByPath(fromObject, new String[] {"pageSize"})); + toObject, + new String[] {"supportedActions"}, + Common.getValueByPath(fromObject, new String[] {"supportedGenerationMethods"})); } - 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[] {"maxTemperature"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_query", "filter"}, - Common.getValueByPath(fromObject, new String[] {"filter"})); + toObject, + new String[] {"maxTemperature"}, + Common.getValueByPath(fromObject, new String[] {"maxTemperature"})); } - if (Common.getValueByPath(fromObject, new String[] {"queryBase"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"_url", "models_url"}, - Transformers.tModelsUrl( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"queryBase"}))); + toObject, + new String[] {"topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"topK"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode listModelsParametersToVertex( - 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[] {"thinking"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - listModelsConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"thinking"}, + Common.getValueByPath(fromObject, new String[] {"thinking"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode updateModelConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode modelFromVertex(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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( - parentObject, + toObject, new String[] {"displayName"}, Common.getValueByPath(fromObject, new String[] {"displayName"})); } if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( - parentObject, + toObject, new String[] {"description"}, Common.getValueByPath(fromObject, new String[] {"description"})); } - if (Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"versionId"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"defaultCheckpointId"}, - Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); + toObject, + new String[] {"version"}, + Common.getValueByPath(fromObject, new String[] {"versionId"})); } - return toObject; - } + 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(); - @ExcludeFromGeneratedCoverageReport - ObjectNode updateModelParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { + for (JsonNode item : keyArray) { + result.add(endpointFromVertex(JsonSerializable.toJsonNode(item), toObject, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"endpoints"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - updateModelConfigToVertex( - apiClient, + new String[] {"tunedModelInfo"}, + tunedModelInfoFromVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject, + rootObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteModelParametersToVertex( - 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[] {"defaultCheckpointId"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "name"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"defaultCheckpointId"}, + Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"checkpoints"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"checkpoints"}, + Common.getValueByPath(fromObject, new String[] {"checkpoints"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"systemInstruction"}) != null) { + ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"systemInstruction"}, - contentToVertex( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tContent( - this.apiClient, - 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(parentObject, new String[] {"tools"}, result); + toObject, + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"generationConfig"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"generationConfig"}, - Common.getValueByPath(fromObject, new String[] {"generationConfig"})); + toObject, + new String[] {"codeExecutionResult"}, + Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensParametersToVertex( - 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[] {"executableCode"}) != 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( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(contentToVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"contents"}, result); + new String[] {"executableCode"}, + Common.getValueByPath(fromObject, new String[] {"executableCode"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - countTokensConfigToVertex( - apiClient, + new String[] {"fileData"}, + fileDataToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"fileData"})), + toObject, + rootObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode computeTokensParametersToVertex( - 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[] {"functionCall"}) != 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( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"contents"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(contentToVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"contents"}, result); + new String[] {"functionCall"}, + functionCallToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"functionCall"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - Common.getValueByPath(fromObject, new String[] {"config"})); + new String[] {"functionResponse"}, + Common.getValueByPath(fromObject, new String[] {"functionResponse"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - if (Common.getValueByPath(fromObject, new String[] {"numberOfVideos"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "sampleCount"}, - Common.getValueByPath(fromObject, new String[] {"numberOfVideos"})); + toObject, + new String[] {"inlineData"}, + blobToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"inlineData"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "storageUri"}, - Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); + toObject, + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "fps"}, - Common.getValueByPath(fromObject, new String[] {"fps"})); + toObject, + new String[] {"thought"}, + Common.getValueByPath(fromObject, new String[] {"thought"})); } - if (Common.getValueByPath(fromObject, new String[] {"durationSeconds"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "durationSeconds"}, - Common.getValueByPath(fromObject, new String[] {"durationSeconds"})); + toObject, + new String[] {"thoughtSignature"}, + Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); } - if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "seed"}, - Common.getValueByPath(fromObject, new String[] {"seed"})); + toObject, + new String[] {"videoMetadata"}, + Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); } - if (Common.getValueByPath(fromObject, new String[] {"aspectRatio"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "aspectRatio"}, - Common.getValueByPath(fromObject, new String[] {"aspectRatio"})); + toObject, + new String[] {"toolCall"}, + Common.getValueByPath(fromObject, new String[] {"toolCall"})); } - if (Common.getValueByPath(fromObject, new String[] {"resolution"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "resolution"}, - Common.getValueByPath(fromObject, new String[] {"resolution"})); + toObject, + new String[] {"toolResponse"}, + Common.getValueByPath(fromObject, new String[] {"toolResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"partMetadata"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "personGeneration"}, - Common.getValueByPath(fromObject, new String[] {"personGeneration"})); + toObject, + new String[] {"partMetadata"}, + Common.getValueByPath(fromObject, new String[] {"partMetadata"})); } - if (Common.getValueByPath(fromObject, new String[] {"pubsubTopic"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode partToVertex(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "pubsubTopic"}, - Common.getValueByPath(fromObject, new String[] {"pubsubTopic"})); + toObject, + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (Common.getValueByPath(fromObject, new String[] {"negativePrompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "negativePrompt"}, - Common.getValueByPath(fromObject, new String[] {"negativePrompt"})); + toObject, + new String[] {"codeExecutionResult"}, + Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); } - if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "enhancePrompt"}, - Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); + toObject, + new String[] {"executableCode"}, + Common.getValueByPath(fromObject, new String[] {"executableCode"})); } - if (Common.getValueByPath(fromObject, new String[] {"generateAudio"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"parameters", "generateAudio"}, - Common.getValueByPath(fromObject, new String[] {"generateAudio"})); + toObject, + new String[] {"fileData"}, + Common.getValueByPath(fromObject, new String[] {"fileData"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosParametersToVertex( - 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[] {"functionCall"}) != null) { Common.setValueByPath( toObject, - new String[] {"_url", "model"}, - Transformers.tModel( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); + new String[] {"functionCall"}, + Common.getValueByPath(fromObject, new String[] {"functionCall"})); } - if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { Common.setValueByPath( toObject, - new String[] {"instances[0]", "prompt"}, - Common.getValueByPath(fromObject, new String[] {"prompt"})); + new String[] {"functionResponse"}, + Common.getValueByPath(fromObject, new String[] {"functionResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { Common.setValueByPath( toObject, - new String[] {"instances[0]", "image"}, - imageToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"image"})), - toObject)); + new String[] {"inlineData"}, + Common.getValueByPath(fromObject, new String[] {"inlineData"})); } - if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( toObject, - new String[] {"config"}, - generateVideosConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"config"})), - toObject)); + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + toObject, + new String[] {"thought"}, + Common.getValueByPath(fromObject, new String[] {"thought"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"thoughtSignature"}, + Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"videoMetadata"}, + Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"toolCall"}))) { + throw new IllegalArgumentException( + "toolCall parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode blobFromMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"toolResponse"}))) { + throw new IllegalArgumentException( + "toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } - 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"})); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"partMetadata"}))) { + throw new IllegalArgumentException( + "partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataFromMldev(ApiClient apiClient, 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) { + ObjectNode productImageToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"productImage"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"image"}, + imageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"productImage"})), + toObject, + rootObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode partFromMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + ObjectNode recontextImageConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + parentObject, + new String[] {"parameters", "sampleCount"}, + Common.getValueByPath(fromObject, new String[] {"numberOfImages"})); } - if (Common.getValueByPath(fromObject, new String[] {"thought"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"baseSteps"}) != null) { Common.setValueByPath( - toObject, - new String[] {"thought"}, - Common.getValueByPath(fromObject, new String[] {"thought"})); + parentObject, + new String[] {"parameters", "baseSteps"}, + Common.getValueByPath(fromObject, new String[] {"baseSteps"})); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { Common.setValueByPath( - toObject, - new String[] {"inlineData"}, - blobFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + parentObject, + new String[] {"parameters", "storageUri"}, + Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"seed"}) != null) { Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + parentObject, + new String[] {"parameters", "seed"}, + Common.getValueByPath(fromObject, new String[] {"seed"})); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { Common.setValueByPath( - toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + parentObject, + new String[] {"parameters", "safetySetting"}, + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { Common.setValueByPath( - toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"addWatermark"}) != null) { Common.setValueByPath( - toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + parentObject, + new String[] {"parameters", "addWatermark"}, + Common.getValueByPath(fromObject, new String[] {"addWatermark"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + parentObject, + new String[] {"parameters", "outputOptions", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + parentObject, + new String[] {"parameters", "outputOptions", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enhancePrompt"}) != null) { Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + parentObject, + new String[] {"parameters", "enhancePrompt"}, + Common.getValueByPath(fromObject, new String[] {"enhancePrompt"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentFromMldev(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(); + ObjectNode recontextImageParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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"}))); + } - for (JsonNode item : keyArray) { - result.add(partFromMldev(apiClient, 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, + rootObject); } - 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, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode citationMetadataFromMldev( - ApiClient apiClient, 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"})); + ObjectNode recontextImageResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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(); + + for (JsonNode item : keyArray) { + result.add( + generatedImageFromVertex(JsonSerializable.toJsonNode(item), toObject, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode urlMetadataFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"retrievedUrl"}) != null) { + ObjectNode recontextImageSourceToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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, + rootObject)); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextMetadataFromMldev( - ApiClient apiClient, 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(urlMetadataFromMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(productImageToVertex(JsonSerializable.toJsonNode(item), toObject, rootObject)); } - Common.setValueByPath(toObject, new String[] {"urlMetadata"}, result); + Common.setValueByPath(parentObject, new String[] {"instances[0]", "productImages"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode candidateFromMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"content"}) != null) { + ObjectNode referenceImageAPIToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"referenceImage"}) != null) { Common.setValueByPath( toObject, - new String[] {"content"}, - contentFromMldev( - apiClient, + new String[] {"referenceImage"}, + imageToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"content"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"referenceImage"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"citationMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"referenceId"}) != null) { Common.setValueByPath( toObject, - new String[] {"citationMetadata"}, - citationMetadataFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"citationMetadata"})), - toObject)); + new String[] {"referenceId"}, + Common.getValueByPath(fromObject, new String[] {"referenceId"})); } - if (Common.getValueByPath(fromObject, new String[] {"tokenCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"referenceType"}) != null) { Common.setValueByPath( toObject, - new String[] {"tokenCount"}, - Common.getValueByPath(fromObject, new String[] {"tokenCount"})); + 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, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"controlImageConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlContextMetadata"}, - urlContextMetadataFromMldev( - apiClient, + new String[] {"controlImageConfig"}, + controlReferenceConfigToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"controlImageConfig"})), + toObject, + rootObject)); } - 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, JsonNode rootObject) { + 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 generateContentResponseFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"candidates"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"modelVersion"}) != null) { + ObjectNode safetyAttributesFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"}) + != null) { Common.setValueByPath( toObject, - new String[] {"modelVersion"}, - Common.getValueByPath(fromObject, new String[] {"modelVersion"})); + new String[] {"categories"}, + Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"})); } - if (Common.getValueByPath(fromObject, new String[] {"promptFeedback"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"}) != null) { Common.setValueByPath( toObject, - new String[] {"promptFeedback"}, - Common.getValueByPath(fromObject, new String[] {"promptFeedback"})); + new String[] {"scores"}, + Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"})); } - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"contentType"}) != null) { Common.setValueByPath( toObject, - new String[] {"usageMetadata"}, - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); + new String[] {"contentType"}, + Common.getValueByPath(fromObject, new String[] {"contentType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentEmbeddingStatisticsFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contentEmbeddingFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"values"}) != null) { + ObjectNode safetySettingToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"category"}) != null) { Common.setValueByPath( toObject, - new String[] {"values"}, - Common.getValueByPath(fromObject, new String[] {"values"})); + new String[] {"category"}, + Common.getValueByPath(fromObject, new String[] {"category"})); } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"method"}))) { + throw new IllegalArgumentException( + "method parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentMetadataFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"threshold"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"threshold"}, + Common.getValueByPath(fromObject, new String[] {"threshold"})); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentResponseFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - 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(); - - for (JsonNode item : keyArray) { - result.add( - contentEmbeddingFromMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"embeddings"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { + ObjectNode scribbleImageToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( toObject, - new String[] {"metadata"}, - embedContentMetadataFromMldev( - apiClient, + new String[] {"image"}, + imageToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"metadata"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject, + rootObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode imageFromMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode segmentImageConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mode"}) != null) { Common.setValueByPath( - toObject, - new String[] {"imageBytes"}, - Transformers.tBytes( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}))); + parentObject, + new String[] {"parameters", "mode"}, + Common.getValueByPath(fromObject, new String[] {"mode"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maxPredictions"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + parentObject, + new String[] {"parameters", "maxPredictions"}, + Common.getValueByPath(fromObject, new String[] {"maxPredictions"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"confidenceThreshold"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "confidenceThreshold"}, + Common.getValueByPath(fromObject, new String[] {"confidenceThreshold"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode safetyAttributesFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"}) - != null) { + if (Common.getValueByPath(fromObject, new String[] {"maskDilation"}) != null) { Common.setValueByPath( - toObject, - new String[] {"categories"}, - Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"})); + parentObject, + new String[] {"parameters", "maskDilation"}, + Common.getValueByPath(fromObject, new String[] {"maskDilation"})); } - if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"binaryColorThreshold"}) != null) { Common.setValueByPath( - toObject, - new String[] {"scores"}, - Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"})); + parentObject, + new String[] {"parameters", "binaryColorThreshold"}, + Common.getValueByPath(fromObject, new String[] {"binaryColorThreshold"})); } - if (Common.getValueByPath(fromObject, new String[] {"contentType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { Common.setValueByPath( - toObject, - new String[] {"contentType"}, - Common.getValueByPath(fromObject, new String[] {"contentType"})); + parentObject, + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generatedImageFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + ObjectNode segmentImageParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"image"}, - imageFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"raiFilteredReason"}, - Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"})); + if (Common.getValueByPath(fromObject, new String[] {"source"}) != null) { + JsonNode unused = + segmentImageSourceToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"source"})), + toObject, + rootObject); } - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"safetyAttributes"}, - safetyAttributesFromMldev( - apiClient, + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + segmentImageConfigToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateImagesResponseFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode segmentImageResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"predictions"}) != null) { ArrayNode keyArray = (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); @@ -4568,1338 +4814,1116 @@ ObjectNode generateImagesResponseFromMldev( ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(generatedImageFromMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add( + generatedImageMaskFromVertex(JsonSerializable.toJsonNode(item), toObject, rootObject)); } - Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"positivePromptSafetyAttributes"}) - != null) { - Common.setValueByPath( - toObject, - new String[] {"positivePromptSafetyAttributes"}, - safetyAttributesFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath( - fromObject, new String[] {"positivePromptSafetyAttributes"})), - toObject)); + Common.setValueByPath(toObject, new String[] {"generatedMasks"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode endpointFromMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode segmentImageSourceToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"image"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"instances[0]", "image"}, + imageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject, + rootObject)); + } + + if (Common.getValueByPath(fromObject, new String[] {"scribbleImage"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"instances[0]", "scribble"}, + scribbleImageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"scribbleImage"})), + toObject, + rootObject)); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode tunedModelInfoFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"baseModel"}) != null) { + ObjectNode toolConfigToMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"baseModel"}, - Common.getValueByPath(fromObject, new String[] {"baseModel"})); + new String[] {"retrievalConfig"}, + Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})); } - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); + new String[] {"functionCallingConfig"}, + functionCallingConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeServerSideToolInvocations"}) + != null) { Common.setValueByPath( toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"updateTime"})); + new String[] {"includeServerSideToolInvocations"}, + Common.getValueByPath(fromObject, new String[] {"includeServerSideToolInvocations"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode checkpointFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode toolConfigToVertex(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"retrievalConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"retrievalConfig"}, + Common.getValueByPath(fromObject, new String[] {"retrievalConfig"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"functionCallingConfig"}, + Common.getValueByPath(fromObject, new String[] {"functionCallingConfig"})); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"includeServerSideToolInvocations"}))) { + throw new IllegalArgumentException( + "includeServerSideToolInvocations parameter is only supported in Gemini Developer API" + + " mode, not in Gemini Enterprise Agent Platform mode."); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode modelFromMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { + throw new IllegalArgumentException( + "retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + 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[] {"displayName"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + new String[] {"fileSearch"}, + Common.getValueByPath(fromObject, new String[] {"fileSearch"})); } - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); + new String[] {"googleSearch"}, + googleSearchToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"googleSearch"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"version"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { Common.setValueByPath( toObject, - new String[] {"version"}, - Common.getValueByPath(fromObject, new String[] {"version"})); + new String[] {"googleMaps"}, + googleMapsToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"googleMaps"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { Common.setValueByPath( toObject, - new String[] {"tunedModelInfo"}, - tunedModelInfoFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); } - if (Common.getValueByPath(fromObject, new String[] {"inputTokenLimit"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { + throw new IllegalArgumentException( + "enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { Common.setValueByPath( toObject, - new String[] {"inputTokenLimit"}, - Common.getValueByPath(fromObject, new String[] {"inputTokenLimit"})); + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); } - if (Common.getValueByPath(fromObject, new String[] {"outputTokenLimit"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"outputTokenLimit"}, - Common.getValueByPath(fromObject, new String[] {"outputTokenLimit"})); + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); } - if (Common.getValueByPath(fromObject, new String[] {"supportedGenerationMethods"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"parallelAiSearch"}))) { + throw new IllegalArgumentException( + "parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { Common.setValueByPath( toObject, - new String[] {"supportedActions"}, - Common.getValueByPath(fromObject, new String[] {"supportedGenerationMethods"})); + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"mcpServers"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mcpServers"}, + Common.getValueByPath(fromObject, new String[] {"mcpServers"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode listModelsResponseFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"nextPageToken"}) != null) { + ObjectNode toolToVertex(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"retrieval"}) != 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( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"_self"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add(modelFromMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"models"}, result); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteModelResponseFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensResponseFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"totalTokens"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"totalTokens"}, - Common.getValueByPath(fromObject, new String[] {"totalTokens"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"cachedContentTokenCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"cachedContentTokenCount"}, - Common.getValueByPath(fromObject, new String[] {"cachedContentTokenCount"})); + new String[] {"retrieval"}, + Common.getValueByPath(fromObject, new String[] {"retrieval"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoFromMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"video", "uri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { Common.setValueByPath( toObject, - new String[] {"uri"}, - Common.getValueByPath(fromObject, new String[] {"video", "uri"})); + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); } - if (Common.getValueByPath(fromObject, new String[] {"video", "encodedVideo"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoBytes"}, - Transformers.tBytes( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"video", "encodedVideo"}))); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"fileSearch"}))) { + throw new IllegalArgumentException( + "fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); } - if (Common.getValueByPath(fromObject, new String[] {"encoding"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"encoding"})); + new String[] {"googleSearch"}, + Common.getValueByPath(fromObject, new String[] {"googleSearch"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generatedVideoFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { Common.setValueByPath( toObject, - new String[] {"video"}, - videoFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosResponseFromMldev( - ApiClient apiClient, 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); + new String[] {"googleMaps"}, + Common.getValueByPath(fromObject, new String[] {"googleMaps"})); } - if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { Common.setValueByPath( toObject, - new String[] {"raiMediaFilteredCount"}, - Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); } - if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"raiMediaFilteredReasons"}, - Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); + new String[] {"enterpriseWebSearch"}, + Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosOperationFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { Common.setValueByPath( toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"name"})); + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); } - if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { Common.setValueByPath( toObject, - new String[] {"metadata"}, - Common.getValueByPath(fromObject, new String[] {"metadata"})); + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); } - if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"parallelAiSearch"}) != null) { Common.setValueByPath( toObject, - new String[] {"done"}, - Common.getValueByPath(fromObject, new String[] {"done"})); + new String[] {"parallelAiSearch"}, + Common.getValueByPath(fromObject, new String[] {"parallelAiSearch"})); } - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { Common.setValueByPath( toObject, - new String[] {"error"}, - Common.getValueByPath(fromObject, new String[] {"error"})); + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); } - if (Common.getValueByPath(fromObject, new String[] {"response", "generateVideoResponse"}) - != null) { - Common.setValueByPath( - toObject, - new String[] {"response"}, - generateVideosResponseFromMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath( - fromObject, new String[] {"response", "generateVideoResponse"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"mcpServers"}))) { + throw new IllegalArgumentException( + "mcpServers parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { + ObjectNode tunedModelInfoFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath( + fromObject, new String[] {"labels", "google-vertex-llm-tuning-base-model-id"}) + != null) { Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + toObject, + new String[] {"baseModel"}, + Common.getValueByPath( + fromObject, new String[] {"labels", "google-vertex-llm-tuning-base-model-id"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + new String[] {"createTime"}, + Common.getValueByPath(fromObject, new String[] {"createTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { Common.setValueByPath( toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + new String[] {"updateTime"}, + Common.getValueByPath(fromObject, new String[] {"updateTime"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode blobFromVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode updateModelConfigToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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[] {"data"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( - toObject, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); + parentObject, + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + parentObject, + new String[] {"defaultCheckpointId"}, + Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataFromVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode updateModelConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { Common.setValueByPath( - toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + parentObject, + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"}) != null) { Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + parentObject, + new String[] {"defaultCheckpointId"}, + Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode partFromVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + ObjectNode updateModelParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoMetadata"}, - videoMetadataFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + new String[] {"_url", "name"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - 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[] {"config"}) != null) { + JsonNode unused = + updateModelConfigToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode updateModelParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"inlineData"}, - blobFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataFromVertex( - apiClient, + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + updateModelConfigToVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } - if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode upscaleImageAPIConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (Common.getValueByPath(fromObject, new String[] {"outputGcsUri"}) != null) { Common.setValueByPath( - toObject, - new String[] {"thoughtSignature"}, - Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); + parentObject, + new String[] {"parameters", "storageUri"}, + Common.getValueByPath(fromObject, new String[] {"outputGcsUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"}) != null) { Common.setValueByPath( - toObject, - new String[] {"codeExecutionResult"}, - Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); + parentObject, + new String[] {"parameters", "safetySetting"}, + Common.getValueByPath(fromObject, new String[] {"safetyFilterLevel"})); } - if (Common.getValueByPath(fromObject, new String[] {"executableCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"personGeneration"}) != null) { Common.setValueByPath( - toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + parentObject, + new String[] {"parameters", "personGeneration"}, + Common.getValueByPath(fromObject, new String[] {"personGeneration"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"includeRaiReason"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); + parentObject, + new String[] {"parameters", "includeRaiReason"}, + Common.getValueByPath(fromObject, new String[] {"includeRaiReason"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputMimeType"}) != null) { Common.setValueByPath( - toObject, - new String[] {"functionResponse"}, - Common.getValueByPath(fromObject, new String[] {"functionResponse"})); + parentObject, + new String[] {"parameters", "outputOptions", "mimeType"}, + Common.getValueByPath(fromObject, new String[] {"outputMimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"}) != null) { Common.setValueByPath( - toObject, - new String[] {"text"}, - Common.getValueByPath(fromObject, new String[] {"text"})); + parentObject, + new String[] {"parameters", "outputOptions", "compressionQuality"}, + Common.getValueByPath(fromObject, new String[] {"outputCompressionQuality"})); } - return toObject; - } + if (Common.getValueByPath(fromObject, new String[] {"enhanceInputImage"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "upscaleConfig", "enhanceInputImage"}, + Common.getValueByPath(fromObject, new String[] {"enhanceInputImage"})); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode contentFromVertex(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[] {"imagePreservationFactor"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"parameters", "upscaleConfig", "imagePreservationFactor"}, + Common.getValueByPath(fromObject, new String[] {"imagePreservationFactor"})); + } - for (JsonNode item : keyArray) { - result.add(partFromVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"parts"}, result); + 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[] {"role"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"numberOfImages"}) != null) { Common.setValueByPath( - toObject, - new String[] {"role"}, - Common.getValueByPath(fromObject, new String[] {"role"})); + 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 citationMetadataFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"citations"}) != null) { + ObjectNode upscaleImageAPIParametersToVertex( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, - new String[] {"citations"}, - Common.getValueByPath(fromObject, new String[] {"citations"})); + new String[] {"_url", "model"}, + Transformers.tModel( + this.apiClient, Common.getValueByPath(fromObject, new String[] {"model"}))); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlMetadataFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"retrievedUrl"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( toObject, - new String[] {"retrievedUrl"}, - Common.getValueByPath(fromObject, new String[] {"retrievedUrl"})); + new String[] {"instances[0]", "image"}, + imageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"urlRetrievalStatus"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"upscaleFactor"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlRetrievalStatus"}, - Common.getValueByPath(fromObject, new String[] {"urlRetrievalStatus"})); + new String[] {"parameters", "upscaleConfig", "upscaleFactor"}, + Common.getValueByPath(fromObject, new String[] {"upscaleFactor"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { + JsonNode unused = + upscaleImageAPIConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject, + rootObject); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextMetadataFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"urlMetadata"}) != null) { + ObjectNode upscaleImageResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"predictions"}) != null) { ArrayNode keyArray = - (ArrayNode) Common.getValueByPath(fromObject, new String[] {"urlMetadata"}); + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"predictions"}); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(urlMetadataFromVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add( + generatedImageFromVertex(JsonSerializable.toJsonNode(item), toObject, rootObject)); } - Common.setValueByPath(toObject, new String[] {"urlMetadata"}, result); + Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode candidateFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"content"}) != null) { + ObjectNode videoFromMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"uri"}) != null) { Common.setValueByPath( - toObject, - new String[] {"content"}, - contentFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"content"})), - toObject)); + toObject, new String[] {"uri"}, Common.getValueByPath(fromObject, new String[] {"uri"})); } - if (Common.getValueByPath(fromObject, new String[] {"citationMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"encodedVideo"}) != null) { Common.setValueByPath( toObject, - new String[] {"citationMetadata"}, - citationMetadataFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"citationMetadata"})), - toObject)); + new String[] {"videoBytes"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"encodedVideo"}))); } - if (Common.getValueByPath(fromObject, new String[] {"finishMessage"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"encoding"}) != null) { Common.setValueByPath( toObject, - new String[] {"finishMessage"}, - Common.getValueByPath(fromObject, new String[] {"finishMessage"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"encoding"})); } - if (Common.getValueByPath(fromObject, new String[] {"finishReason"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"finishReason"}, - Common.getValueByPath(fromObject, new String[] {"finishReason"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode videoFromVertex(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { Common.setValueByPath( toObject, - new String[] {"urlContextMetadata"}, - urlContextMetadataFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"urlContextMetadata"})), - toObject)); + new String[] {"uri"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); } - if (Common.getValueByPath(fromObject, new String[] {"avgLogprobs"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}) != null) { Common.setValueByPath( toObject, - new String[] {"avgLogprobs"}, - Common.getValueByPath(fromObject, new String[] {"avgLogprobs"})); + new String[] {"videoBytes"}, + Transformers.tBytes( + Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}))); } - if (Common.getValueByPath(fromObject, new String[] {"groundingMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"groundingMetadata"}, - Common.getValueByPath(fromObject, new String[] {"groundingMetadata"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } - if (Common.getValueByPath(fromObject, new String[] {"index"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"index"}, - Common.getValueByPath(fromObject, new String[] {"index"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"logprobsResult"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode videoGenerationMaskToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( toObject, - new String[] {"logprobsResult"}, - Common.getValueByPath(fromObject, new String[] {"logprobsResult"})); + new String[] {"_self"}, + imageToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"safetyRatings"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"maskMode"}) != null) { Common.setValueByPath( toObject, - new String[] {"safetyRatings"}, - Common.getValueByPath(fromObject, new String[] {"safetyRatings"})); + new String[] {"maskMode"}, + Common.getValueByPath(fromObject, new String[] {"maskMode"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generateContentResponseFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"candidates"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { + ObjectNode videoGenerationReferenceImageToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"image"}) != null) { Common.setValueByPath( toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); + new String[] {"image"}, + imageToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"image"})), + toObject, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"responseId"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"referenceType"}) != null) { + videoGenerationReferenceTypeMldevEnumValidate( + Common.getValueByPath(fromObject, new String[] {"referenceType"})); Common.setValueByPath( toObject, - new String[] {"responseId"}, - Common.getValueByPath(fromObject, new String[] {"responseId"})); + new String[] {"referenceType"}, + Common.getValueByPath(fromObject, new String[] {"referenceType"})); } - if (Common.getValueByPath(fromObject, new String[] {"modelVersion"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"modelVersion"}, - Common.getValueByPath(fromObject, new String[] {"modelVersion"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"promptFeedback"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode videoGenerationReferenceImageToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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, + rootObject)); } - if (Common.getValueByPath(fromObject, new String[] {"usageMetadata"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"referenceType"}) != null) { Common.setValueByPath( toObject, - new String[] {"usageMetadata"}, - Common.getValueByPath(fromObject, new String[] {"usageMetadata"})); + new String[] {"referenceType"}, + Common.getValueByPath(fromObject, new String[] {"referenceType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentEmbeddingStatisticsFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"truncated"}) != null) { + ObjectNode videoToMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"videoBytes"}) != null) { Common.setValueByPath( toObject, - new String[] {"truncated"}, - Common.getValueByPath(fromObject, new String[] {"truncated"})); + new String[] {"encodedVideo"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"videoBytes"}))); } - if (Common.getValueByPath(fromObject, new String[] {"token_count"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"tokenCount"}, - Common.getValueByPath(fromObject, new String[] {"token_count"})); + new String[] {"encoding"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode contentEmbeddingFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"values"}) != null) { + ObjectNode videoToVertex(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"uri"}) != null) { Common.setValueByPath( toObject, - new String[] {"values"}, - Common.getValueByPath(fromObject, new String[] {"values"})); + new String[] {"gcsUri"}, + Common.getValueByPath(fromObject, new String[] {"uri"})); } - if (Common.getValueByPath(fromObject, new String[] {"statistics"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"videoBytes"}) != null) { Common.setValueByPath( toObject, - new String[] {"statistics"}, - contentEmbeddingStatisticsFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"statistics"})), - toObject)); + new String[] {"bytesBase64Encoded"}, + Transformers.tBytes(Common.getValueByPath(fromObject, new String[] {"videoBytes"}))); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentMetadataFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"billableCharacterCount"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { Common.setValueByPath( toObject, - new String[] {"billableCharacterCount"}, - Common.getValueByPath(fromObject, new String[] {"billableCharacterCount"})); + new String[] {"mimeType"}, + Common.getValueByPath(fromObject, new String[] {"mimeType"})); } return toObject; } - @ExcludeFromGeneratedCoverageReport - ObjectNode embedContentResponseFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"predictions[]", "embeddings"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Common.getValueByPath(fromObject, new String[] {"predictions[]", "embeddings"}); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateGenerateContent( + String model, List contents, GenerateContentConfig config) { - for (JsonNode item : keyArray) { - result.add( - contentEmbeddingFromVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"embeddings"}, result); - } + GenerateContentParameters.Builder parameterBuilder = GenerateContentParameters.builder(); - if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"metadata"}, - embedContentMetadataFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"metadata"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode imageFromVertex(ApiClient apiClient, 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.isZero(model)) { + parameterBuilder.model(model); } - - if (Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"imageBytes"}, - Transformers.tBytes( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}))); + if (!Common.isZero(contents)) { + parameterBuilder.contents(contents); } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + if (!Common.isZero(config)) { + parameterBuilder.config(config); } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode safetyAttributesFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"}) - != null) { - Common.setValueByPath( - toObject, - new String[] {"categories"}, - Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "categories"})); + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = generateContentParametersToVertex(this.apiClient, parameterNode, null, parameterNode); + path = Common.formatMap("{model}:generateContent", body.get("_url")); + } else { + body = generateContentParametersToMldev(this.apiClient, parameterNode, null, parameterNode); + if (body.get("_url") != null) { + path = Common.formatMap("{model}:generateContent", body.get("_url")); + } else { + path = "{model}:generateContent"; + } } + body.remove("_url"); - if (Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"scores"}, - Common.getValueByPath(fromObject, new String[] {"safetyAttributes", "scores"})); + JsonNode queryParams = body.get("_query"); + if (queryParams != null) { + body.remove("_query"); + path = String.format("%s?%s", path, Common.urlEncode((ObjectNode) queryParams)); } - if (Common.getValueByPath(fromObject, new String[] {"contentType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"contentType"}, - Common.getValueByPath(fromObject, new String[] {"contentType"})); + // TODO: Remove the hack that removes config. + Optional requestHttpOptions = Optional.empty(); + if (config != null) { + requestHttpOptions = config.httpOptions(); } - return toObject; + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); } - @ExcludeFromGeneratedCoverageReport - ObjectNode generatedImageFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"image"}, - imageFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"raiFilteredReason"}, - Common.getValueByPath(fromObject, new String[] {"raiFilteredReason"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"safetyAttributes"}, - safetyAttributesFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); + /** A shared processResponse function for both sync and async methods. */ + GenerateContentResponse processResponseForPrivateGenerateContent( + ApiResponse response, GenerateContentConfig config, JsonNode parameterNode) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); } - if (Common.getValueByPath(fromObject, new String[] {"prompt"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"enhancedPrompt"}, - Common.getValueByPath(fromObject, new String[] {"prompt"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateImagesResponseFromVertex( - ApiClient apiClient, 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(); - - for (JsonNode item : keyArray) { - result.add( - generatedImageFromVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); + if (config != null && config.shouldReturnHttpResponse().orElse(false)) { + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return GenerateContentResponse.builder() + .sdkHttpResponse(HttpResponse.builder().body(responseString)) + .build(); } - Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"positivePromptSafetyAttributes"}) - != null) { - Common.setValueByPath( - toObject, - new String[] {"positivePromptSafetyAttributes"}, - safetyAttributesFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath( - fromObject, new String[] {"positivePromptSafetyAttributes"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode editImageResponseFromVertex( - ApiClient apiClient, 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(); - - for (JsonNode item : keyArray) { - result.add( - generatedImageFromVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); } - Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); + return GenerateContentResponse.builder() + .sdkHttpResponse(HttpResponse.builder().headers(headers).body(responseString)) + .build(); } - return toObject; - } + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - @ExcludeFromGeneratedCoverageReport - ObjectNode upscaleImageResponseFromVertex( - ApiClient apiClient, 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(); - - for (JsonNode item : keyArray) { - result.add( - generatedImageFromVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"generatedImages"}, result); + if (this.apiClient.vertexAI()) { + responseNode = generateContentResponseFromVertex(responseNode, null, parameterNode); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode endpointFromVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"endpoint"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"name"}, - Common.getValueByPath(fromObject, new String[] {"endpoint"})); + if (!this.apiClient.vertexAI()) { + responseNode = generateContentResponseFromMldev(responseNode, null, parameterNode); } - if (Common.getValueByPath(fromObject, new String[] {"deployedModelId"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"deployedModelId"}, - Common.getValueByPath(fromObject, new String[] {"deployedModelId"})); + GenerateContentResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, GenerateContentResponse.class); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders == null) { + return sdkResponse; } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode tunedModelInfoFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath( - fromObject, new String[] {"labels", "google-vertex-llm-tuning-base-model-id"}) - != null) { - Common.setValueByPath( - toObject, - new String[] {"baseModel"}, - Common.getValueByPath( - fromObject, new String[] {"labels", "google-vertex-llm-tuning-base-model-id"})); + Map headers = new HashMap<>(); + for (String headerName : responseHeaders.names()) { + headers.put(headerName, responseHeaders.get(headerName)); } + return sdkResponse.toBuilder().sdkHttpResponse(HttpResponse.builder().headers(headers)).build(); + } - if (Common.getValueByPath(fromObject, new String[] {"createTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"createTime"}, - Common.getValueByPath(fromObject, new String[] {"createTime"})); - } + GenerateContentResponse privateGenerateContent( + String model, List contents, GenerateContentConfig config) { + GenerateContentParameters.Builder parameterBuilder = GenerateContentParameters.builder(); - if (Common.getValueByPath(fromObject, new String[] {"updateTime"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"updateTime"}, - Common.getValueByPath(fromObject, new String[] {"updateTime"})); + if (!Common.isZero(model)) { + parameterBuilder.model(model); } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode checkpointFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"checkpointId"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"checkpointId"}, - Common.getValueByPath(fromObject, new String[] {"checkpointId"})); + if (!Common.isZero(contents)) { + parameterBuilder.contents(contents); } - - if (Common.getValueByPath(fromObject, new String[] {"epoch"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"epoch"}, - Common.getValueByPath(fromObject, new String[] {"epoch"})); + if (!Common.isZero(config)) { + parameterBuilder.config(config); } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = buildRequestForPrivateGenerateContent(model, contents, config); - if (Common.getValueByPath(fromObject, new String[] {"step"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"step"}, - Common.getValueByPath(fromObject, new String[] {"step"})); + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateGenerateContent(response, config, parameterNode); } - - return toObject; } - @ExcludeFromGeneratedCoverageReport - ObjectNode modelFromVertex(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) { - Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); - } + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateGenerateContentStream( + String model, List contents, GenerateContentConfig config) { - if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"description"}, - Common.getValueByPath(fromObject, new String[] {"description"})); - } + GenerateContentParameters.Builder parameterBuilder = GenerateContentParameters.builder(); - if (Common.getValueByPath(fromObject, new String[] {"versionId"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"version"}, - Common.getValueByPath(fromObject, new String[] {"versionId"})); + if (!Common.isZero(model)) { + parameterBuilder.model(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(); - - for (JsonNode item : keyArray) { - result.add(endpointFromVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"endpoints"}, result); + if (!Common.isZero(contents)) { + parameterBuilder.contents(contents); } - - if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"labels"}, - Common.getValueByPath(fromObject, new String[] {"labels"})); + if (!Common.isZero(config)) { + parameterBuilder.config(config); } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"tunedModelInfo"}, - tunedModelInfoFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = generateContentParametersToVertex(this.apiClient, parameterNode, null, parameterNode); + path = Common.formatMap("{model}:streamGenerateContent?alt=sse", body.get("_url")); + } else { + body = generateContentParametersToMldev(this.apiClient, parameterNode, null, parameterNode); + if (body.get("_url") != null) { + path = Common.formatMap("{model}:streamGenerateContent?alt=sse", body.get("_url")); + } else { + path = "{model}:streamGenerateContent?alt=sse"; + } } + body.remove("_url"); - if (Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"defaultCheckpointId"}, - Common.getValueByPath(fromObject, new String[] {"defaultCheckpointId"})); + JsonNode queryParams = body.get("_query"); + if (queryParams != null) { + body.remove("_query"); + path = String.format("%s?%s", path, Common.urlEncode((ObjectNode) queryParams)); } - 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"checkpoints"}, result); + // TODO: Remove the hack that removes config. + Optional requestHttpOptions = Optional.empty(); + if (config != null) { + requestHttpOptions = config.httpOptions(); } - return toObject; + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); } - @ExcludeFromGeneratedCoverageReport - ObjectNode listModelsResponseFromVertex( - ApiClient apiClient, 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[] {"_self"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tExtractModels( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"_self"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); + /** A shared processResponse function for both sync and async methods. */ + ResponseStream processResponseForPrivateGenerateContentStream( + ApiResponse response, GenerateContentConfig config, JsonNode parameterNode) { + String converterName; - for (JsonNode item : keyArray) { - result.add(modelFromVertex(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"models"}, result); + if (this.apiClient.vertexAI()) { + converterName = "generateContentResponseFromVertex"; + } else { + converterName = "generateContentResponseFromMldev"; } - - return toObject; + return new ResponseStream( + GenerateContentResponse.class, response, this, converterName, true, true); } - @ExcludeFromGeneratedCoverageReport - ObjectNode deleteModelResponseFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } + ResponseStream privateGenerateContentStream( + String model, List contents, GenerateContentConfig config) { + GenerateContentParameters.Builder parameterBuilder = GenerateContentParameters.builder(); - @ExcludeFromGeneratedCoverageReport - ObjectNode countTokensResponseFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"totalTokens"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"totalTokens"}, - Common.getValueByPath(fromObject, new String[] {"totalTokens"})); + 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()); + BuiltRequest builtRequest = + buildRequestForPrivateGenerateContentStream(model, contents, config); - return toObject; + ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions()); + return processResponseForPrivateGenerateContentStream(response, config, parameterNode); } - @ExcludeFromGeneratedCoverageReport - ObjectNode computeTokensResponseFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"tokensInfo"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"tokensInfo"}, - Common.getValueByPath(fromObject, new String[] {"tokensInfo"})); - } + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateEmbedContent( + String model, + List contents, + Content content, + EmbeddingApiType embeddingApiType, + EmbedContentConfig config) { - return toObject; - } + EmbedContentParametersPrivate.Builder parameterBuilder = + EmbedContentParametersPrivate.builder(); - @ExcludeFromGeneratedCoverageReport - ObjectNode videoFromVertex(ApiClient apiClient, 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.isZero(model)) { + parameterBuilder.model(model); } - - if (Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoBytes"}, - Transformers.tBytes( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"bytesBase64Encoded"}))); + if (!Common.isZero(contents)) { + parameterBuilder.contents(contents); } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + if (!Common.isZero(content)) { + parameterBuilder.content(content); } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generatedVideoFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"_self"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"video"}, - videoFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), - toObject)); + if (!Common.isZero(embeddingApiType)) { + parameterBuilder.embeddingApiType(embeddingApiType); } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosResponseFromVertex( - ApiClient apiClient, 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = + embedContentParametersPrivateToVertex(this.apiClient, parameterNode, null, parameterNode); + String endpointUrl = + Transformers.tIsVertexEmbedContentModel( + ((JsonNode) Common.getValueByPath(parameterNode, new String[] {"model"})) + .asText()) + ? "{model}:embedContent" + : "{model}:predict"; + path = Common.formatMap(endpointUrl, body.get("_url")); + } else { + body = + embedContentParametersPrivateToMldev(this.apiClient, parameterNode, null, parameterNode); + if (body.get("_url") != null) { + path = Common.formatMap("{model}:batchEmbedContents", body.get("_url")); + } else { + path = "{model}:batchEmbedContents"; } - Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); } + body.remove("_url"); - if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"raiMediaFilteredCount"}, - Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"})); + JsonNode queryParams = body.get("_query"); + if (queryParams != null) { + body.remove("_query"); + path = String.format("%s?%s", path, Common.urlEncode((ObjectNode) queryParams)); } - if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"raiMediaFilteredReasons"}, - Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); + // TODO: Remove the hack that removes config. + Optional requestHttpOptions = Optional.empty(); + if (config != null) { + requestHttpOptions = config.httpOptions(); } - return toObject; + return new BuiltRequest(path, JsonSerializable.toJsonString(body), requestHttpOptions); } - @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosOperationFromVertex( - 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"})); + /** A shared processResponse function for both sync and async methods. */ + EmbedContentResponse processResponseForPrivateEmbedContent( + ApiResponse response, EmbedContentConfig config, JsonNode parameterNode) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); } - if (Common.getValueByPath(fromObject, new String[] {"metadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"metadata"}, - Common.getValueByPath(fromObject, new String[] {"metadata"})); + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); + + if (this.apiClient.vertexAI()) { + responseNode = embedContentResponseFromVertex(responseNode, null, parameterNode); } - if (Common.getValueByPath(fromObject, new String[] {"done"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"done"}, - Common.getValueByPath(fromObject, new String[] {"done"})); + if (!this.apiClient.vertexAI()) { + responseNode = embedContentResponseFromMldev(responseNode, null, parameterNode); } - if (Common.getValueByPath(fromObject, new String[] {"error"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"error"}, - Common.getValueByPath(fromObject, new String[] {"error"})); + 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(); + } - if (Common.getValueByPath(fromObject, new String[] {"response"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"response"}, - generateVideosResponseFromVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"response"})), - toObject)); + EmbedContentResponse privateEmbedContent( + String model, + List contents, + Content content, + EmbeddingApiType embeddingApiType, + EmbedContentConfig config) { + EmbedContentParametersPrivate.Builder parameterBuilder = + EmbedContentParametersPrivate.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(contents)) { + parameterBuilder.contents(contents); + } + if (!Common.isZero(content)) { + parameterBuilder.content(content); + } + if (!Common.isZero(embeddingApiType)) { + parameterBuilder.embeddingApiType(embeddingApiType); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = + buildRequestForPrivateEmbedContent(model, contents, content, embeddingApiType, config); - return toObject; + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateEmbedContent(response, config, parameterNode); + } } - GenerateContentResponse privateGenerateContent( - String model, List contents, GenerateContentConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateGenerateImages( + String model, String prompt, GenerateImagesConfig config) { - GenerateContentParameters.Builder parameterBuilder = GenerateContentParameters.builder(); + GenerateImagesParameters.Builder parameterBuilder = GenerateImagesParameters.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(config)) { parameterBuilder.config(config); @@ -5909,14 +5933,14 @@ GenerateContentResponse privateGenerateContent( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = generateContentParametersToVertex(this.apiClient, parameterNode, null); - path = Common.formatMap("{model}:generateContent", body.get("_url")); + body = generateImagesParametersToVertex(this.apiClient, parameterNode, null, parameterNode); + path = Common.formatMap("{model}:predict", body.get("_url")); } else { - body = generateContentParametersToMldev(this.apiClient, parameterNode, null); + body = generateImagesParametersToMldev(this.apiClient, parameterNode, null, parameterNode); if (body.get("_url") != null) { - path = Common.formatMap("{model}:generateContent", body.get("_url")); + path = Common.formatMap("{model}:predict", body.get("_url")); } else { - path = "{model}:generateContent"; + path = "{model}:predict"; } } body.remove("_url"); @@ -5928,44 +5952,89 @@ GenerateContentResponse privateGenerateContent( } // 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. */ + GenerateImagesResponse processResponseForPrivateGenerateImages( + ApiResponse response, GenerateImagesConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + responseNode = generateImagesResponseFromMldev(responseNode, null, parameterNode); + } + + 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(); + } + + /** Private method for generating images. */ + GenerateImagesResponse privateGenerateImages( + 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()); + BuiltRequest builtRequest = buildRequestForPrivateGenerateImages(model, prompt, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = generateContentResponseFromVertex(this.apiClient, responseNode, null); - } else { - responseNode = generateContentResponseFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, GenerateContentResponse.class); + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateGenerateImages(response, config, parameterNode); } } - ResponseStream privateGenerateContentStream( - String model, List contents, GenerateContentConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateEditImage( + String model, + String prompt, + List referenceImages, + EditImageConfig config) { - GenerateContentParameters.Builder parameterBuilder = GenerateContentParameters.builder(); + 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); @@ -5975,15 +6044,12 @@ ResponseStream privateGenerateContentStream( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = generateContentParametersToVertex(this.apiClient, parameterNode, null); - path = Common.formatMap("{model}:streamGenerateContent?alt=sse", body.get("_url")); + body = editImageParametersToVertex(this.apiClient, parameterNode, null, parameterNode); + path = Common.formatMap("{model}:predict", body.get("_url")); } else { - body = generateContentParametersToMldev(this.apiClient, parameterNode, null); - if (body.get("_url") != null) { - path = Common.formatMap("{model}:streamGenerateContent?alt=sse", body.get("_url")); - } else { - path = "{model}:streamGenerateContent?alt=sse"; - } + throw new UnsupportedOperationException( + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); } body.remove("_url"); @@ -5994,37 +6060,95 @@ ResponseStream privateGenerateContentStream( } // TODO: Remove the hack that removes config. - body.remove("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. */ + EditImageResponse processResponseForPrivateEditImage( + ApiResponse response, EditImageConfig config, JsonNode parameterNode) { + 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 = editImageResponseFromVertex(responseNode, null, parameterNode); } - return new ResponseStream( - GenerateContentResponse.class, response, this, converterName); + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } + + 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(); } - EmbedContentResponse privateEmbedContent( - String model, List contents, EmbedContentConfig config) { + /** Private method for editing an image. */ + EditImageResponse privateEditImage( + String model, + String prompt, + List referenceImages, + EditImageConfig config) { + EditImageParameters.Builder parameterBuilder = EditImageParameters.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(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = + buildRequestForPrivateEditImage(model, prompt, referenceImages, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateEditImage(response, config, parameterNode); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateUpscaleImage( + String model, Image image, String upscaleFactor, UpscaleImageAPIConfig config) { - EmbedContentParameters.Builder parameterBuilder = EmbedContentParameters.builder(); + UpscaleImageAPIParameters.Builder parameterBuilder = UpscaleImageAPIParameters.builder(); if (!Common.isZero(model)) { parameterBuilder.model(model); } - if (!Common.isZero(contents)) { - parameterBuilder.contents(contents); + if (!Common.isZero(image)) { + parameterBuilder.image(image); + } + if (!Common.isZero(upscaleFactor)) { + parameterBuilder.upscaleFactor(upscaleFactor); } if (!Common.isZero(config)) { parameterBuilder.config(config); @@ -6034,15 +6158,12 @@ EmbedContentResponse privateEmbedContent( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = embedContentParametersToVertex(this.apiClient, parameterNode, null); + body = upscaleImageAPIParametersToVertex(this.apiClient, parameterNode, null, parameterNode); 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 Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); } body.remove("_url"); @@ -6053,44 +6174,89 @@ 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. */ + UpscaleImageResponse processResponseForPrivateUpscaleImage( + ApiResponse response, UpscaleImageAPIConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } + + 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) { + UpscaleImageAPIParameters.Builder parameterBuilder = UpscaleImageAPIParameters.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(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = + buildRequestForPrivateUpscaleImage(model, image, upscaleFactor, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = embedContentResponseFromVertex(this.apiClient, responseNode, null); - } else { - responseNode = embedContentResponseFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, EmbedContentResponse.class); + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateUpscaleImage(response, config, parameterNode); } } - GenerateImagesResponse privateGenerateImages( - String model, String prompt, GenerateImagesConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForRecontextImage( + String model, RecontextImageSource source, RecontextImageConfig config) { - GenerateImagesParameters.Builder parameterBuilder = GenerateImagesParameters.builder(); + RecontextImageParameters.Builder parameterBuilder = RecontextImageParameters.builder(); if (!Common.isZero(model)) { parameterBuilder.model(model); } - if (!Common.isZero(prompt)) { - parameterBuilder.prompt(prompt); + if (!Common.isZero(source)) { + parameterBuilder.source(source); } if (!Common.isZero(config)) { parameterBuilder.config(config); @@ -6100,15 +6266,12 @@ GenerateImagesResponse privateGenerateImages( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = generateImagesParametersToVertex(this.apiClient, parameterNode, null); + body = recontextImageParametersToVertex(this.apiClient, parameterNode, null, parameterNode); 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 Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); } body.remove("_url"); @@ -6119,50 +6282,90 @@ 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. */ + RecontextImageResponse processResponseForRecontextImage( + ApiResponse response, RecontextImageConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } + + return JsonSerializable.fromJsonNode(responseNode, RecontextImageResponse.class); + } + + /** + * Recontextualizes an image. + * + *

    There is one type of recontextualization currently supported: 1) 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 behind an + * allowlist. personImage is required. productImages is required. Only one product image is + * supported currently. + * @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) { + RecontextImageParameters.Builder parameterBuilder = RecontextImageParameters.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(source)) { + parameterBuilder.source(source); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = buildRequestForRecontextImage(model, source, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = generateImagesResponseFromVertex(this.apiClient, responseNode, null); - } else { - responseNode = generateImagesResponseFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, GenerateImagesResponse.class); + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForRecontextImage(response, config, parameterNode); } } - EditImageResponse privateEditImage( - String model, - String prompt, - List referenceImages, - EditImageConfig config) { + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForSegmentImage( + String model, SegmentImageSource source, SegmentImageConfig config) { - EditImageParameters.Builder parameterBuilder = EditImageParameters.builder(); + SegmentImageParameters.Builder parameterBuilder = SegmentImageParameters.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); @@ -6172,11 +6375,12 @@ EditImageResponse privateEditImage( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = editImageParametersToVertex(this.apiClient, parameterNode, null); + body = segmentImageParametersToVertex(this.apiClient, parameterNode, null, parameterNode); path = Common.formatMap("{model}:predict", body.get("_url")); } else { throw new UnsupportedOperationException( - "This method is not supported by the Gemini Developer API."); + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); } body.remove("_url"); @@ -6187,48 +6391,83 @@ EditImageResponse privateEditImage( } // 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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } 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 = editImageResponseFromVertex(this.apiClient, responseNode, null); - } else { - throw new UnsupportedOperationException( - "This method is not supported by the Gemini Developer API."); - } - return JsonSerializable.fromJsonNode(responseNode, EditImageResponse.class); + /** A shared processResponse function for both sync and async methods. */ + SegmentImageResponse processResponseForSegmentImage( + ApiResponse response, SegmentImageConfig config, JsonNode parameterNode) { + ResponseBody responseBody = response.getBody(); + String responseString; + try { + responseString = responseBody.string(); + } catch (IOException e) { + throw new GenAiIOException("Failed to read HTTP response.", e); } - } - UpscaleImageResponse privateUpscaleImage( - String model, Image image, String upscaleFactor, UpscaleImageAPIConfig config) { + JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - UpscaleImageAPIParameters.Builder parameterBuilder = UpscaleImageAPIParameters.builder(); + if (this.apiClient.vertexAI()) { + responseNode = segmentImageResponseFromVertex(responseNode, null, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } + + return JsonSerializable.fromJsonNode(responseNode, SegmentImageResponse.class); + } + + /** + * 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 SegmentImageResponse segmentImage( + String model, SegmentImageSource source, SegmentImageConfig config) { + SegmentImageParameters.Builder parameterBuilder = SegmentImageParameters.builder(); if (!Common.isZero(model)) { parameterBuilder.model(model); } - if (!Common.isZero(image)) { - parameterBuilder.image(image); + if (!Common.isZero(source)) { + parameterBuilder.source(source); } - if (!Common.isZero(upscaleFactor)) { - parameterBuilder.upscaleFactor(upscaleFactor); + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = buildRequestForSegmentImage(model, source, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForSegmentImage(response, config, parameterNode); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForGet(String model, GetModelConfig config) { + + GetModelParameters.Builder parameterBuilder = GetModelParameters.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); } if (!Common.isZero(config)) { parameterBuilder.config(config); @@ -6238,11 +6477,15 @@ UpscaleImageResponse privateUpscaleImage( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = upscaleImageAPIParametersToVertex(this.apiClient, parameterNode, null); - path = Common.formatMap("{model}:predict", body.get("_url")); + body = getModelParametersToVertex(this.apiClient, parameterNode, null, parameterNode); + path = Common.formatMap("{name}", body.get("_url")); } else { - throw new UnsupportedOperationException( - "This method is not supported by the Gemini Developer API."); + body = getModelParametersToMldev(this.apiClient, parameterNode, null, parameterNode); + if (body.get("_url") != null) { + path = Common.formatMap("{name}", body.get("_url")); + } else { + path = "{name}"; + } } body.remove("_url"); @@ -6253,33 +6496,35 @@ 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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } 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(this.apiClient, responseNode, null); - } else { - throw new UnsupportedOperationException( - "This method is not supported by the Gemini Developer API."); - } - return JsonSerializable.fromJsonNode(responseNode, UpscaleImageResponse.class); + /** A shared processResponse function for both sync and async methods. */ + Model processResponseForGet(ApiResponse response, GetModelConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + responseNode = modelFromMldev(responseNode, null, parameterNode); + } + + return JsonSerializable.fromJsonNode(responseNode, Model.class); } /** @@ -6288,12 +6533,29 @@ UpscaleImageResponse privateUpscaleImage( * @example ```java Model model = client.models.get("gemini-2.0-flash"); ``` */ public Model get(String model, GetModelConfig config) { - GetModelParameters.Builder parameterBuilder = GetModelParameters.builder(); if (!Common.isZero(model)) { parameterBuilder.model(model); } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = buildRequestForGet(model, config); + + try (ApiResponse response = + this.apiClient.request( + "get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForGet(response, config, parameterNode); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateList(ListModelsConfig config) { + + ListModelsParameters.Builder parameterBuilder = ListModelsParameters.builder(); + if (!Common.isZero(config)) { parameterBuilder.config(config); } @@ -6302,14 +6564,14 @@ public Model get(String model, GetModelConfig config) { ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = getModelParametersToVertex(this.apiClient, parameterNode, null); - path = Common.formatMap("{name}", body.get("_url")); + body = listModelsParametersToVertex(this.apiClient, parameterNode, null, parameterNode); + path = Common.formatMap("{models_url}", body.get("_url")); } else { - body = getModelParametersToMldev(this.apiClient, parameterNode, null); + body = listModelsParametersToMldev(this.apiClient, parameterNode, null, parameterNode); if (body.get("_url") != null) { - path = Common.formatMap("{name}", body.get("_url")); + path = Common.formatMap("{models_url}", body.get("_url")); } else { - path = "{name}"; + path = "{models_url}"; } } body.remove("_url"); @@ -6321,38 +6583,72 @@ 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(); } - try (ApiResponse response = - this.apiClient.request( - "get", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } 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 = modelFromVertex(this.apiClient, responseNode, null); - } else { - responseNode = modelFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, Model.class); + /** A shared processResponse function for both sync and async methods. */ + ListModelsResponse processResponseForPrivateList( + ApiResponse response, ListModelsConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + responseNode = listModelsResponseFromMldev(responseNode, null, parameterNode); } + + 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) { - ListModelsParameters.Builder parameterBuilder = ListModelsParameters.builder(); + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = buildRequestForPrivateList(config); + + try (ApiResponse response = + this.apiClient.request( + "get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateList(response, config, parameterNode); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForUpdate(String model, UpdateModelConfig config) { + + UpdateModelParameters.Builder parameterBuilder = UpdateModelParameters.builder(); + + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } if (!Common.isZero(config)) { parameterBuilder.config(config); } @@ -6361,14 +6657,14 @@ ListModelsResponse privateList(ListModelsConfig config) { ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = listModelsParametersToVertex(this.apiClient, parameterNode, null); - path = Common.formatMap("{models_url}", body.get("_url")); + body = updateModelParametersToVertex(this.apiClient, parameterNode, null, parameterNode); + path = Common.formatMap("{model}", body.get("_url")); } else { - body = listModelsParametersToMldev(this.apiClient, parameterNode, null); + body = updateModelParametersToMldev(this.apiClient, parameterNode, null, parameterNode); if (body.get("_url") != null) { - path = Common.formatMap("{models_url}", body.get("_url")); + path = Common.formatMap("{name}", body.get("_url")); } else { - path = "{models_url}"; + path = "{name}"; } } body.remove("_url"); @@ -6380,32 +6676,36 @@ ListModelsResponse privateList(ListModelsConfig 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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } 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 = listModelsResponseFromVertex(this.apiClient, responseNode, null); - } else { - responseNode = listModelsResponseFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, ListModelsResponse.class); + /** A shared processResponse function for both sync and async methods. */ + Model processResponseForUpdate( + ApiResponse response, UpdateModelConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + responseNode = modelFromMldev(responseNode, null, parameterNode); } + + return JsonSerializable.fromJsonNode(responseNode, Model.class); } /** @@ -6420,9 +6720,29 @@ ListModelsResponse privateList(ListModelsConfig config) { * description") .build()); ``` */ public Model update(String model, UpdateModelConfig config) { - UpdateModelParameters.Builder parameterBuilder = UpdateModelParameters.builder(); + if (!Common.isZero(model)) { + parameterBuilder.model(model); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = buildRequestForUpdate(model, config); + + try (ApiResponse response = + this.apiClient.request( + "patch", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForUpdate(response, config, parameterNode); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForDelete(String model, DeleteModelConfig config) { + + DeleteModelParameters.Builder parameterBuilder = DeleteModelParameters.builder(); + if (!Common.isZero(model)) { parameterBuilder.model(model); } @@ -6434,10 +6754,10 @@ public Model update(String model, UpdateModelConfig config) { ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = updateModelParametersToVertex(this.apiClient, parameterNode, null); - path = Common.formatMap("{model}", body.get("_url")); + body = deleteModelParametersToVertex(this.apiClient, parameterNode, null, parameterNode); + path = Common.formatMap("{name}", body.get("_url")); } else { - body = updateModelParametersToMldev(this.apiClient, parameterNode, null); + body = deleteModelParametersToMldev(this.apiClient, parameterNode, null, parameterNode); if (body.get("_url") != null) { path = Common.formatMap("{name}", body.get("_url")); } else { @@ -6453,32 +6773,46 @@ 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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } 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 = modelFromVertex(this.apiClient, responseNode, null); - } else { - responseNode = modelFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, Model.class); + /** A shared processResponse function for both sync and async methods. */ + DeleteModelResponse processResponseForDelete( + ApiResponse response, DeleteModelConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + responseNode = deleteModelResponseFromMldev(responseNode, null, parameterNode); } + + 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(); } /** @@ -6487,7 +6821,6 @@ public Model update(String model, UpdateModelConfig config) { * @example ```java Model model = client.models.delete("tunedModels/12345"); ``` */ public DeleteModelResponse delete(String model, DeleteModelConfig config) { - DeleteModelParameters.Builder parameterBuilder = DeleteModelParameters.builder(); if (!Common.isZero(model)) { @@ -6497,18 +6830,43 @@ public DeleteModelResponse delete(String model, DeleteModelConfig config) { parameterBuilder.config(config); } JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = buildRequestForDelete(model, config); + + try (ApiResponse response = + this.apiClient.request( + "delete", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForDelete(response, config, parameterNode); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForCountTokens( + String model, List contents, CountTokensConfig config) { + + CountTokensParameters.Builder parameterBuilder = CountTokensParameters.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 = deleteModelParametersToVertex(this.apiClient, parameterNode, null); - path = Common.formatMap("{name}", body.get("_url")); + body = countTokensParametersToVertex(this.apiClient, parameterNode, null, parameterNode); + path = Common.formatMap("{model}:countTokens", body.get("_url")); } else { - body = deleteModelParametersToMldev(this.apiClient, parameterNode, null); + body = countTokensParametersToMldev(this.apiClient, parameterNode, null, parameterNode); if (body.get("_url") != null) { - path = Common.formatMap("{name}", body.get("_url")); + path = Common.formatMap("{model}:countTokens", body.get("_url")); } else { - path = "{name}"; + path = "{model}:countTokens"; } } body.remove("_url"); @@ -6520,32 +6878,46 @@ 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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } 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(this.apiClient, responseNode, null); - } else { - responseNode = deleteModelResponseFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, DeleteModelResponse.class); + /** A shared processResponse function for both sync and async methods. */ + CountTokensResponse processResponseForCountTokens( + ApiResponse response, CountTokensConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + responseNode = countTokensResponseFromMldev(responseNode, null, parameterNode); + } + + 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(); } /** @@ -6560,8 +6932,32 @@ public DeleteModelResponse delete(String model, DeleteModelConfig config) { */ public CountTokensResponse countTokens( String model, List contents, CountTokensConfig config) { + CountTokensParameters.Builder parameterBuilder = CountTokensParameters.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()); + BuiltRequest builtRequest = buildRequestForCountTokens(model, contents, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForCountTokens(response, config, parameterNode); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForComputeTokens( + String model, List contents, ComputeTokensConfig config) { - CountTokensParameters.Builder parameterBuilder = CountTokensParameters.builder(); + ComputeTokensParameters.Builder parameterBuilder = ComputeTokensParameters.builder(); if (!Common.isZero(model)) { parameterBuilder.model(model); @@ -6577,15 +6973,12 @@ public CountTokensResponse countTokens( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = countTokensParametersToVertex(this.apiClient, parameterNode, null); - path = Common.formatMap("{model}:countTokens", body.get("_url")); + body = computeTokensParametersToVertex(this.apiClient, parameterNode, null, parameterNode); + path = Common.formatMap("{model}:computeTokens", body.get("_url")); } else { - body = countTokensParametersToMldev(this.apiClient, parameterNode, null); - if (body.get("_url") != null) { - path = Common.formatMap("{model}:countTokens", body.get("_url")); - } else { - path = "{model}:countTokens"; - } + throw new UnsupportedOperationException( + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); } body.remove("_url"); @@ -6596,32 +6989,48 @@ 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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } 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(this.apiClient, responseNode, null); - } else { - responseNode = countTokensResponseFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, CountTokensResponse.class); + /** A shared processResponse function for both sync and async methods. */ + ComputeTokensResponse processResponseForComputeTokens( + ApiResponse response, ComputeTokensConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } + + 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(); } /** @@ -6636,7 +7045,6 @@ public CountTokensResponse countTokens( */ public ComputeTokensResponse computeTokens( String model, List contents, ComputeTokensConfig config) { - ComputeTokensParameters.Builder parameterBuilder = ComputeTokensParameters.builder(); if (!Common.isZero(model)) { @@ -6649,69 +7057,23 @@ public ComputeTokensResponse computeTokens( parameterBuilder.config(config); } JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); - - ObjectNode body; - String path; - if (this.apiClient.vertexAI()) { - body = computeTokensParametersToVertex(this.apiClient, parameterNode, null); - path = Common.formatMap("{model}:computeTokens", body.get("_url")); - } else { - throw new UnsupportedOperationException( - "This method is not supported by the Gemini Developer API."); - } - 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. - body.remove("config"); - - Optional requestHttpOptions = Optional.empty(); - if (config != null) { - requestHttpOptions = config.httpOptions(); - } + BuiltRequest builtRequest = buildRequestForComputeTokens(model, contents, config); try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = computeTokensResponseFromVertex(this.apiClient, responseNode, null); - } else { - throw new UnsupportedOperationException( - "This method is not supported by the Gemini Developer API."); - } - return JsonSerializable.fromJsonNode(responseNode, ComputeTokensResponse.class); + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForComputeTokens(response, config, parameterNode); } } - /** - * Generates videos given a GenAI model, and a prompt or an image. - * - *

    This method is experimental. - * - * @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 use cases. - * @param image the input image for generating the videos. Optional if prompt is provided. - * @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, String prompt, Image image, GenerateVideosConfig 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(); @@ -6724,6 +7086,12 @@ public GenerateVideosOperation generateVideos( if (!Common.isZero(image)) { parameterBuilder.image(image); } + if (!Common.isZero(video)) { + parameterBuilder.video(video); + } + if (!Common.isZero(source)) { + parameterBuilder.source(source); + } if (!Common.isZero(config)) { parameterBuilder.config(config); } @@ -6732,10 +7100,10 @@ public GenerateVideosOperation generateVideos( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = generateVideosParametersToVertex(this.apiClient, parameterNode, null); + body = generateVideosParametersToVertex(this.apiClient, parameterNode, null, parameterNode); path = Common.formatMap("{model}:predictLongRunning", body.get("_url")); } else { - body = generateVideosParametersToMldev(this.apiClient, parameterNode, null); + body = generateVideosParametersToMldev(this.apiClient, parameterNode, null, parameterNode); if (body.get("_url") != null) { path = Common.formatMap("{model}:predictLongRunning", body.get("_url")); } else { @@ -6751,31 +7119,74 @@ public GenerateVideosOperation generateVideos( } // 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, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + responseNode = generateVideosOperationFromMldev(responseNode, null, parameterNode); + } + + 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) { + GenerateVideosParameters.Builder parameterBuilder = GenerateVideosParameters.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(video)) { + parameterBuilder.video(video); + } + if (!Common.isZero(source)) { + parameterBuilder.source(source); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = + buildRequestForPrivateGenerateVideos(model, prompt, image, video, source, config); + try (ApiResponse response = this.apiClient.request( - "post", path, JsonSerializable.toJsonString(body), requestHttpOptions)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = generateVideosOperationFromVertex(this.apiClient, responseNode, null); - } else { - responseNode = generateVideosOperationFromMldev(this.apiClient, responseNode, null); - } - return JsonSerializable.fromJsonNode(responseNode, GenerateVideosOperation.class); + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateGenerateVideos(response, config, parameterNode); } } @@ -6793,11 +7204,26 @@ public GenerateVideosOperation generateVideos( */ public GenerateContentResponse generateContent( String model, List contents, GenerateContentConfig config) { - GenerateContentConfig transformedConfig = - AfcUtil.transformGenerateContentConfig(apiClient, config); + ImmutableList incompatibleToolsIndexes = + AfcUtil.findAfcIncompatibleToolIndexes(config); + GenerateContentConfig transformedConfig = AfcUtil.transformGenerateContentConfig(config); if (AfcUtil.shouldDisableAfc(transformedConfig)) { return privateGenerateContent(model, contents, transformedConfig); } + if (!incompatibleToolsIndexes.isEmpty()) { + int originalToolsSize = 0; + if (config.tools().isPresent() && !config.tools().get().isEmpty()) { + originalToolsSize = config.tools().get().size(); + } + if (originalToolsSize != incompatibleToolsIndexes.size()) { + logger.warning( + String.format( + "Automatic function calling (AFC) is enabled, but the following tools are not" + + " supported: %s. AFC will be disabled.", + incompatibleToolsIndexes)); + } + return privateGenerateContent(model, contents, transformedConfig); + } ImmutableMap functionMap = AfcUtil.getFunctionMap(config); if (functionMap.isEmpty()) { return privateGenerateContent(model, contents, transformedConfig); @@ -6889,10 +7315,8 @@ public GenerateContentResponse generateContent( */ public ResponseStream generateContentStream( String model, List contents, GenerateContentConfig config) { - GenerateContentConfig transformedConfig = - AfcUtil.transformGenerateContentConfig(apiClient, config); - if (AfcUtil.hasCallableTool(apiClient, config) - && !AfcUtil.shouldDisableAfc(transformedConfig)) { + 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" @@ -6962,21 +7386,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<>(); @@ -7004,8 +7415,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)); } /** @@ -7014,12 +7439,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 @@ -7036,6 +7462,45 @@ public EditImageResponse editImage( return privateEditImage(model, prompt, referenceImagesAPI, 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()); + } + if (config.enhanceInputImage().isPresent()) { + builder = builder.enhanceInputImage(config.enhanceInputImage().get()); + } + 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); + + return builder.build(); + } + /** * Upscales an image given a GenAI model and an image and an upscale factor. * @@ -7049,26 +7514,107 @@ public EditImageResponse editImage( */ public UpscaleImageResponse upscaleImage( String model, Image image, String upscaleFactor, UpscaleImageConfig config) { + return privateUpscaleImage(model, image, upscaleFactor, preProcessUpscaleImageConfig(config)); + } - UpscaleImageAPIConfig.Builder builder = UpscaleImageAPIConfig.builder(); - if (config != null) { - if (config.outputMimeType().isPresent()) { - builder = builder.outputMimeType(config.outputMimeType().get()); - } - if (config.outputCompressionQuality().isPresent()) { - builder = builder.outputCompressionQuality(config.outputCompressionQuality().get()); - } - if (config.includeRaiReason().isPresent()) { - builder = builder.includeRaiReason(config.includeRaiReason().get()); + /** 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; + } - builder = builder.mode("upscale"); - builder = builder.numberOfImages(1); + /** + * 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); + } + + /** 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; + } - UpscaleImageAPIConfig apiConfig = builder.build(); + /** + * Generates videos given a GenAI model, and an input (text, image, or video). + * + *

    This method is experimental. + * + * @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 + * optional configurations + * @return a {@link com.google.genai.types.GenerateVideosOperation} instance that contains the + * generated videos. + */ + public GenerateVideosOperation generateVideos( + String model, String prompt, Image image, Video video, GenerateVideosConfig config) { + return privateGenerateVideos(model, prompt, image, preProcessVideo(video), null, config); + } - return privateUpscaleImage(model, image, upscaleFactor, apiConfig); + /** + * Generates videos given a GenAI model, and an input (text, image). + * + *

    This method is experimental, and kept for backward compatibility. + * + * @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 use cases. + * @param image the input image for generating the videos. Optional if prompt is provided. + * @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, String prompt, Image image, GenerateVideosConfig config) { + return generateVideos(model, prompt, image, null, config); } /** @@ -7083,6 +7629,31 @@ public EmbedContentResponse embedContent(String model, String text, EmbedContent return embedContent(model, ImmutableList.of(text), config); } + /** + * Embeds content given a GenAI model and a content object. + * + * @param model the name of the GenAI model to use for embedding + * @param content the {@link com.google.genai.types.Content} to send to the embedding model + * @return a {@link com.google.genai.types.EmbedContentResponse} instance that contains the + * embedding. + */ + public EmbedContentResponse embedContent( + String model, Content content, EmbedContentConfig config) { + List contents = new ArrayList<>(); + contents.add(content); + boolean isVertexEmbedContentModel = + this.apiClient.vertexAI() && Transformers.tIsVertexEmbedContentModel(model); + if (isVertexEmbedContentModel && contents.size() > 1) { + throw new IllegalArgumentException( + "The embedContent API for this model only supports one content at a time."); + } + EmbeddingApiType apiType = + isVertexEmbedContentModel + ? new EmbeddingApiType("EMBED_CONTENT") + : new EmbeddingApiType("PREDICT"); + return privateEmbedContent(model, contents, content, apiType, config); + } + /** * Embeds content given a GenAI model and a list of text strings. * @@ -7097,7 +7668,55 @@ public EmbedContentResponse embedContent( for (String text : texts) { contents.add(Content.fromParts(Part.fromText(text))); } - return privateEmbedContent(model, contents, config); + Content content = null; + if (!contents.isEmpty()) { + content = contents.get(0); + } + boolean isVertexEmbedContentModel = + this.apiClient.vertexAI() && Transformers.tIsVertexEmbedContentModel(model); + if (isVertexEmbedContentModel && contents.size() > 1) { + throw new IllegalArgumentException( + "The embedContent API for this model only supports one content at a time."); + } + EmbeddingApiType apiType = + isVertexEmbedContentModel + ? new EmbeddingApiType("EMBED_CONTENT") + : new EmbeddingApiType("PREDICT"); + return privateEmbedContent(model, contents, content, apiType, config); + } + + /** + * Private method for embedding content, taking either a single content object or a list of + * content objects. + */ + EmbedContentResponse embedContentTest(String model, Object contents, EmbedContentConfig config) { + List contentList = new ArrayList<>(); + if (contents instanceof String) { + contentList.add(Content.fromParts(Part.fromText((String) contents))); + } else if (contents instanceof List) { + List contentsObjectList = (List) contents; + for (Object item : contentsObjectList) { + contentList.add(JsonSerializable.objectMapper.convertValue(item, Content.class)); + } + } else { + throw new IllegalArgumentException("Unsupported contents type: " + contents.getClass()); + } + + Content content = null; + if (contentList != null && !contentList.isEmpty()) { + content = contentList.get(0); + } + boolean isVertexEmbedContentModel = + this.apiClient.vertexAI() && Transformers.tIsVertexEmbedContentModel(model); + if (isVertexEmbedContentModel && contentList.size() > 1) { + throw new IllegalArgumentException( + "The embedContent API for this model only supports one content at a time."); + } + EmbeddingApiType apiType = + isVertexEmbedContentModel + ? new EmbeddingApiType("EMBED_CONTENT") + : new EmbeddingApiType("PREDICT"); + return privateEmbedContent(model, contentList, content, apiType, config); } /** diff --git a/src/main/java/com/google/genai/Operations.java b/src/main/java/com/google/genai/Operations.java index 7e077527f80..35f2ac56abd 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,10 +30,10 @@ 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 org.apache.http.HttpEntity; -import org.apache.http.util.EntityUtils; +import okhttp3.ResponseBody; /** * Provides methods for managing the long-running operations. Instantiating this class is not @@ -42,6 +43,7 @@ *

    This module is experimental. */ public final class Operations { + final ApiClient apiClient; public Operations(ApiClient apiClient) { @@ -49,116 +51,109 @@ public Operations(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode getOperationParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + 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( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"operationName"}) != null) { + ObjectNode generateVideosOperationFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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( - ApiClient apiClient, 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(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"video", "uri"}) != null) { + ObjectNode generateVideosOperationFromVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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( - this.apiClient, - 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( - ApiClient apiClient, 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( - apiClient, + new String[] {"response"}, + generateVideosResponseFromVertex( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"_self"})), + Common.getValueByPath(fromObject, new String[] {"response"})), toObject)); } @@ -166,9 +161,8 @@ ObjectNode generatedVideoFromMldev( } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosResponseFromMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + 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"}); @@ -176,7 +170,7 @@ ObjectNode generateVideosResponseFromMldev( ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add(generatedVideoFromMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); + result.add(generatedVideoFromMldev(JsonSerializable.toJsonNode(item), toObject)); } Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); } @@ -199,92 +193,60 @@ ObjectNode generateVideosResponseFromMldev( } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosOperationFromMldev( - 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[] {"metadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"metadata"}, - Common.getValueByPath(fromObject, new String[] {"metadata"})); - } + 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(); - 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( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath( - fromObject, new String[] {"response", "generateVideoResponse"})), - toObject)); + new String[] {"raiMediaFilteredReasons"}, + Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredReasons"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoFromVertex(ApiClient apiClient, 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) { + ObjectNode generatedVideoFromMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"video"}) != null) { Common.setValueByPath( toObject, - new String[] {"videoBytes"}, - Transformers.tBytes( - this.apiClient, - 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"})); + new String[] {"video"}, + videoFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"video"})), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode generatedVideoFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + 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( - apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"_self"})), toObject)); @@ -294,85 +256,86 @@ ObjectNode generatedVideoFromVertex( } @ExcludeFromGeneratedCoverageReport - ObjectNode generateVideosResponseFromVertex( - ApiClient apiClient, 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(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"generatedVideos"}, result); - } - - if (Common.getValueByPath(fromObject, new String[] {"raiMediaFilteredCount"}) != null) { + ObjectNode getOperationParametersToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { + 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[] {"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( - apiClient, - 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(); @@ -388,10 +351,10 @@ GenerateVideosOperation privateGetVideosOperation( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = getOperationParametersToVertex(this.apiClient, parameterNode, null); + body = getOperationParametersToVertex(parameterNode, null); path = Common.formatMap("{operationName}", body.get("_url")); } else { - body = getOperationParametersToMldev(this.apiClient, parameterNode, null); + body = getOperationParametersToMldev(parameterNode, null); if (body.get("_url") != null) { path = Common.formatMap("{operationName}", body.get("_url")); } else { @@ -407,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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = generateVideosOperationFromVertex(this.apiClient, responseNode, null); - } else { - responseNode = generateVideosOperationFromMldev(this.apiClient, 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 = @@ -455,11 +423,12 @@ GenerateVideosOperation privateFetchPredictVideosOperation( ObjectNode body; String path; if (this.apiClient.vertexAI()) { - body = fetchPredictOperationParametersToVertex(this.apiClient, parameterNode, null); + body = fetchPredictOperationParametersToVertex(parameterNode, null); path = Common.formatMap("{resourceName}:fetchPredictOperation", body.get("_url")); } else { throw new UnsupportedOperationException( - "This method is not supported by the Gemini Developer API."); + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); } body.remove("_url"); @@ -470,32 +439,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)) { - HttpEntity entity = response.getEntity(); - String responseString; - try { - responseString = EntityUtils.toString(entity); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } - - JsonNode responseNode = JsonSerializable.stringToJsonNode(responseString); - if (this.apiClient.vertexAI()) { - responseNode = generateVideosOperationFromVertex(this.apiClient, responseNode, null); - } else { - throw new UnsupportedOperationException( - "This method is not supported by the Gemini Developer API."); - } - return JsonSerializable.fromJsonNode(responseNode, GenerateVideosOperation.class); + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateFetchPredictVideosOperation(response, config); } } @@ -508,20 +482,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..c0816203095 --- /dev/null +++ b/src/main/java/com/google/genai/OperationsConverters.java @@ -0,0 +1,506 @@ +/* + * 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 only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"resourceName"}))) { + throw new IllegalArgumentException( + "resourceName parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"config"}))) { + throw new IllegalArgumentException( + "config parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + 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 importFileOperationFromMldev(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"}, + importFileResponseFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"response"})), + toObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode importFileResponseFromMldev(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[] {"parent"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"parent"}, + Common.getValueByPath(fromObject, new String[] {"parent"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"documentName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"documentName"}, + Common.getValueByPath(fromObject, new String[] {"documentName"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode uploadToFileSearchStoreOperationFromMldev( + 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"}, + uploadToFileSearchStoreResponseFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"response"})), + toObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + @InternalApi + public ObjectNode uploadToFileSearchStoreResponseFromMldev( + 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[] {"parent"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"parent"}, + Common.getValueByPath(fromObject, new String[] {"parent"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"documentName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"documentName"}, + Common.getValueByPath(fromObject, new String[] {"documentName"})); + } + + 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 0b77174624b..57f3abfc486 100644 --- a/src/main/java/com/google/genai/ReplayApiClient.java +++ b/src/main/java/com/google/genai/ReplayApiClient.java @@ -19,50 +19,57 @@ import static com.google.common.base.Preconditions.checkNotNull; import static java.util.stream.Collectors.joining; -import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.api.core.InternalApi; import com.google.auth.oauth2.GoogleCredentials; +import com.google.common.collect.ImmutableMap; import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.ClientOptions; import com.google.genai.types.HttpOptions; -import java.io.ByteArrayInputStream; +import com.google.genai.types.ReplayFile; +import com.google.genai.types.ReplayInteraction; +import com.google.genai.types.ReplayRequest; +import com.google.genai.types.ReplayResponse; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; +import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; -import org.apache.http.Header; -import org.apache.http.ProtocolVersion; -import org.apache.http.StatusLine; -import org.apache.http.entity.BasicHttpEntity; -import org.apache.http.message.BasicHeader; -import org.apache.http.message.BasicStatusLine; - -// TODO(b/369384123): Currently the ReplayApiClient mirrors the HttpApiClient. We will refactor the -// ReplayApiClient to use the ReplayFile as part of resolving b/369384123. +import okhttp3.Headers; +import okhttp3.MediaType; +import okhttp3.Request; +import okhttp3.RequestBody; +import okio.Buffer; /** Base client for the HTTP APIs. */ +@InternalApi @ExcludeFromGeneratedCoverageReport -final class ReplayApiClient extends ApiClient { +public final class ReplayApiClient extends ApiClient { + private final String clientMode; private final String replaysDirectory; private String replayId; - private final String clientMode; - private Map replaySession = null; - private int replayIndex = -1; + private int replayInteractionIndex; + private List replayInteractions; /** Constructs an ApiClient for Google AI APIs. */ - ReplayApiClient( + public ReplayApiClient( Optional apiKey, Optional httpOptions, + Optional clientOptions, String replaysDirectory, String replayId, String clientMode) { - super(apiKey, httpOptions); + super(apiKey, httpOptions, clientOptions); checkNotNull(replaysDirectory, "replaysDirectory cannot be null"); checkNotNull(replayId, "replayId cannot be null"); checkNotNull(clientMode, "clientMode cannot be null"); @@ -73,15 +80,17 @@ final class ReplayApiClient extends ApiClient { } /** Constructs an ApiClient for Vertex AI APIs. */ - ReplayApiClient( + public ReplayApiClient( + Optional apiKey, Optional project, Optional location, Optional credentials, Optional httpOptions, + Optional clientOptions, String replaysDirectory, String replayId, String clientMode) { - super(project, location, credentials, httpOptions); + super(apiKey, project, location, credentials, httpOptions, clientOptions); checkNotNull(replaysDirectory, "replaysDirectory cannot be null"); checkNotNull(replayId, "replayId cannot be null"); checkNotNull(clientMode, "clientMode cannot be null"); @@ -91,101 +100,312 @@ final class ReplayApiClient extends ApiClient { this.clientMode = clientMode; } + /** Reads a string from a file path. */ static String readString(Path path) { try (Stream stream = Files.lines(path)) { return stream.collect(joining(System.lineSeparator())); } catch (IOException e) { - throw new GenAiIOException("Failed to read replay file. ", e); - } - } - - static Map loadReplayData(String replayId) { - String replaysPath = System.getenv("GOOGLE_GENAI_REPLAYS_DIRECTORY"); - if (replaysPath == null) { - throw new RuntimeException("GOOGLE_GENAI_REPLAYS_DIRECTORY is not set"); - } - String testsReplaysPath = replaysPath + "/tests"; - String replayPath = testsReplaysPath + "/" + replayId; - // Open the replay file if it exists. - try { - String replayData = readString(Paths.get(replayPath)); - // TODO(b/369384123): Parsing to a ReplaySession object is not working because snake_case - // fields like body_segments are not being populated. For now, we will just use basic JSON - // parsing and switch to the generated JSON classes once we have the replays working. - // convert JSON string to Map - return JsonSerializable.objectMapper.readValue( - replayData, new TypeReference>() {}); - } catch (IOException e) { - throw new GenAiIOException("Failed to read replay file: " + e, e); + throw new GenAiIOException("Failed to read replay file from path: " + path.toString(), e); } } - void initializeReplaySession(String replayId) { + /** Initializes the replay session. */ + public void initializeReplaySession(String replayId) { this.replayId = replayId; String replayPath = this.replaysDirectory + "/" + this.replayId; - // Open the replay file if it exists. - try { - String replayData = readString(Paths.get(replayPath)); - // TODO(b/369384123): Parsing to a ReplaySession object is not working because snake_case - // fields like body_segments are not being populated. For now, we will just use basic JSON - // parsing and switch to the generated JSON classes once we have the replays working. - // convert JSON string to Map - Map map = - JsonSerializable.objectMapper.readValue( - replayData, new TypeReference>() {}); - this.replaySession = map; - this.replayIndex = 0; - } catch (IOException e) { - throw new GenAiIOException("Failed to read replay file: " + e, e); - } + String replayData = readString(Paths.get(replayPath)); + this.replayInteractions = + ReplayFile.fromJson(replayData) + .interactions() + .orElseThrow( + () -> + new GenAiIOException( + String.format( + "The replay file %s does not have interactions.", replayPath))); + this.replayInteractionIndex = 0; } /** Sends a Http Post request given the path and request json string. */ - @SuppressWarnings("unchecked") @Override public ApiResponse request( String httpMethod, String path, String requestJson, Optional httpOptions) { - if (this.clientMode.equals("replay") || this.clientMode.equals("auto")) { - System.out.println(" === Using replay for ID: " + this.replayId); - List interactions = Arrays.asList(this.replaySession.get("interactions")); - // TODO(b/369384123): Ensure the replay is correctly loaded by index for multi-turn - // conversations. - Object currentInteraction = Arrays.asList(interactions.get(this.replayIndex)).get(0); - LinkedHashMap currentMember = - ((ArrayList>) currentInteraction).get(0); - Map responseMap = (Map) currentMember.get("response"); - Integer statusCode = (Integer) responseMap.get("status_code"); - List bodySegments = (List) responseMap.get("body_segments"); - Map headerMap = (Map) responseMap.get("headers"); - StringBuilder responseBody = new StringBuilder(); - for (Object bodySegment : bodySegments) { - responseBody.append(bodySegment.toString()); - } - - Header[] headers = headerMap.entrySet() - .stream() - .map(entry -> new BasicHeader(entry.getKey(), entry.getValue())) - .toArray(Header[]::new); - - String responseString = responseBody.toString(); - - BasicHttpEntity entity = new BasicHttpEntity(); - entity.setContent(new ByteArrayInputStream(responseString.getBytes(StandardCharsets.UTF_8))); - entity.setContentLength(responseString.length()); - - StatusLine statusLine = - new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), statusCode, "OK"); - - return new ReplayApiResponse(entity, statusLine, headers); + if (this.clientMode.equals("replay")) { + ReplayInteraction currentInteraction = replayInteractions.get(this.replayInteractionIndex); + this.replayInteractionIndex++; + matchRequest( + currentInteraction.request().orElse(null), + buildRequest(httpMethod, path, requestJson, httpOptions)); + boolean isStream = + currentInteraction + .request() + .flatMap(r -> r.url()) + .map(u -> u.contains("streamGenerateContent")) + .orElse(false); + return buildResponseFromReplay(currentInteraction.response().orElse(null), isStream); } else { // Note that if the client mode is "api", then the ReplayApiClient will not be used. throw new IllegalArgumentException("Invalid client mode: " + this.clientMode); } } + /** Sends a Http request given the http method, path, request bytes, and http options. */ @Override public ApiResponse request( String httpMethod, String path, byte[] requestBytes, Optional httpOptions) { 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) { + throw new IllegalArgumentException("Replay request is null."); + } + + // Match request method. + String replayMethod = replayRequest.method().orElse("").toLowerCase(Locale.ROOT); + String actualMethod = actualRequest.method().toLowerCase(Locale.ROOT); + if (!equalsIgnoreKeyCase(replayMethod, actualMethod)) { + throw new AssertionError( + String.format( + "Request method mismatch:\nReplay: %s\nActual: %s", replayMethod, actualMethod)); + } + + // Match request url. + String replayPath = formatUrl(replayRequest.url().orElse("")); + String actualPath = redactRequestUrl(actualRequest.url().toString()); + if (!equalsIgnoreKeyCase(replayPath, actualPath)) { + throw new AssertionError( + String.format("Request url mismatch:\nReplay: %s\nActual: %s", replayPath, actualPath)); + } + + // Match request headers. + Map replayHeaders = replayRequest.headers().orElse(ImmutableMap.of()); + Map actualHeaders = new HashMap<>(); + Map> headersMap = actualRequest.headers().toMultimap(); + for (Map.Entry> entry : headersMap.entrySet()) { + actualHeaders.put(entry.getKey(), String.join(" ", entry.getValue())); + } + actualHeaders = redactRequestHeaders(actualHeaders); + if (!equalsIgnoreKeyCase(replayHeaders, actualHeaders)) { + throw new AssertionError( + String.format( + "Request headers mismatch:\nReplay: %s\nActual: %s", replayHeaders, actualHeaders)); + } + + // Match request body. + if (actualMethod.equals("get") || actualMethod.equals("delete")) { + // No body for these request methods. + return; + } + JsonNode actualBody = + redactRequestBody( + JsonSerializable.stringToJsonNode(requestBodyToString(actualRequest.body()))); + JsonNode replayBody = + JsonSerializable.toJsonNode(replayRequest.bodySegments().orElse(new ArrayList<>()).get(0)); + if (!equalsIgnoreKeyCase(replayBody, actualBody)) { + throw new AssertionError( + String.format( + "Request body mismatch:\nReplay: %s\nAfter key normalization: %s\nActual: %s", + replayBody, normalizeKeyCase(replayBody), actualBody)); + } + } + + /** Builds the response from a {@link ReplayResponse}. */ + private ReplayApiResponse buildResponseFromReplay( + ReplayResponse replayResponse, boolean isStream) { + if (replayResponse == null) { + throw new IllegalArgumentException("Replay response is null."); + } + JsonNode bodyNode = + JsonSerializable.toJsonNode(replayResponse.bodySegments().orElse(new ArrayList<>())); + Headers headers = Headers.of(replayResponse.headers().orElse(ImmutableMap.of())); + return new ReplayApiResponse( + (ArrayNode) bodyNode, replayResponse.statusCode().orElse(0), headers, isStream); + } + + private static String formatUrl(String url) { + String result = url.replace("True", "true"); + result = result.replace("False", "false"); + return result; + } + + /** + * Redact all the url parts before the resource name, so the test can work against any project, + * location, version, or whether it's GCP Express (API keys on Vertex AI). + */ + private static String redactRequestUrl(String requestUrl) { + String result = + requestUrl.replaceAll(".*/projects/[^/]+/locations/[^/]+/", "{VERTEX_URL_PREFIX}/"); + + result = result.replaceAll(".*-aiplatform.googleapis.com/[^/]+/", "{VERTEX_URL_PREFIX}/"); + + result = result.replaceAll(".*aiplatform.googleapis.com/[^/]+/", "{VERTEX_URL_PREFIX}/"); + + result = + result.replaceAll("https://generativelanguage.googleapis.com/[^/]+", "{MLDEV_URL_PREFIX}"); + + return result; + } + + /** Redact all the request headers that are not robust to replay files. */ + private static Map redactRequestHeaders(Map headers) { + Map redactedHeaders = new HashMap<>(); + + for (Map.Entry entry : headers.entrySet()) { + String headerName = entry.getKey(); + String headerValue = entry.getValue(); + + switch (headerName.toLowerCase(Locale.ROOT)) { + case "x-goog-api-key": + redactedHeaders.put(headerName, "{REDACTED}"); + break; + + case "user-agent": + case "x-goog-api-client": + String redactedValue = + headerValue + .replaceAll("\\d+\\.\\d+\\.\\d+", "{VERSION_NUMBER}") + .replace("gl-java/", "{LANGUAGE_LABEL}/"); + redactedHeaders.put(headerName, redactedValue); + break; + + case "x-goog-user-project": + case "authorization": + break; + + default: + redactedHeaders.put(headerName, headerValue); + break; + } + } + return redactedHeaders; + } + + /** Redact the request body to make it robust to replay files. */ + private static JsonNode redactRequestBody(JsonNode requestBody) { + ObjectNode redactedNode = JsonSerializable.objectMapper.createObjectNode(); + requestBody + .fields() + .forEachRemaining( + entry -> { + if (entry.getValue().isTextual()) { + redactedNode.set( + entry.getKey(), + JsonSerializable.toJsonNode( + entry + .getValue() + .asText() + .replaceAll( + "projects/[^/]+/locations/[^/]+/", + "{PROJECT_AND_LOCATION_PATH}/"))); + } else { + redactedNode.set(entry.getKey(), entry.getValue()); + } + }); + return redactedNode; + } + + /** + * Normalizes the key casing(snake vs camel) for a given object. + * + *

    e.g., {'my_key': 'my_value'} -> {'myKey': 'myValue'} + */ + @SuppressWarnings("PatternMatchingInstanceOf") + private static Object normalizeKeyCase(Object obj) { + if (obj instanceof Map) { + Map originalMap = (Map) obj; + Map normalizedMap = new HashMap<>(); + for (Map.Entry entry : originalMap.entrySet()) { + String key = (String) entry.getKey(); + normalizedMap.put( + Common.snakeToCamel(key).toLowerCase(Locale.ROOT), normalizeKeyCase(entry.getValue())); + } + return normalizedMap; + } else if (obj instanceof List) { + List originalList = (List) obj; + List normalizedList = new ArrayList<>(); + for (Object item : originalList) { + normalizedList.add(normalizeKeyCase(item)); + } + return normalizedList; + } else if (obj instanceof JsonNode) { + JsonNode node = (JsonNode) obj; + if (node.isObject()) { + ObjectNode normalizedNode = JsonSerializable.objectMapper.createObjectNode(); + node.fields() + .forEachRemaining( + entry -> { + String newKey = Common.snakeToCamel(entry.getKey()); + Object normalizedValue = normalizeKeyCase(entry.getValue()); + normalizedNode.set(newKey, JsonSerializable.toJsonNode(normalizedValue)); + }); + return normalizedNode; + } else if (node.isArray()) { + ArrayNode normalizedNode = JsonSerializable.objectMapper.createArrayNode(); + node.elements() + .forEachRemaining( + item -> { + normalizedNode.add(JsonSerializable.toJsonNode(normalizeKeyCase(item))); + }); + return normalizedNode; + } else if (node.isTextual()) { + // In the replay file, the timestamp has +00:00 offset, while in the + // actual request it uses Z to represent the offset. We need to + // replace it to match the replay file. + return JsonSerializable.toJsonNode(node.asText().replaceAll("(?<=00)Z$", "\\+00:00")); + } + } + return obj; + } + + /** + * Compares two objects for equality ignoring key casing(snake vs camel). + * + *

    e.g., {'my_key': 'my_value'} and {'myKey': 'my_value'} are considered equal. + */ + private static boolean equalsIgnoreKeyCase(Object replay, Object actual) { + Object normalizedReplay = normalizeKeyCase(replay); + Object normalizedActual = normalizeKeyCase(actual); + + return Objects.equals(normalizedReplay, normalizedActual); + } + + /** Converts a {@link RequestBody} to a string. */ + private static String requestBodyToString(final RequestBody requestBody) { + if (requestBody == null) { + return "No RequestBody"; + } + try { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + MediaType contentType = requestBody.contentType(); + if (contentType != null && contentType.charset() != null) { + return buffer.readString(contentType.charset()); + } else { + return buffer.readUtf8(); + } + } catch (final IOException e) { + throw new GenAiIOException("Failed to convert request body to string.", e); + } + } } diff --git a/src/main/java/com/google/genai/ReplayApiResponse.java b/src/main/java/com/google/genai/ReplayApiResponse.java index 99de3628abe..4e58bb70b49 100644 --- a/src/main/java/com/google/genai/ReplayApiResponse.java +++ b/src/main/java/com/google/genai/ReplayApiResponse.java @@ -16,32 +16,74 @@ package com.google.genai; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.StatusLine; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.google.api.core.InternalApi; +import com.google.genai.errors.ApiException; +import com.google.genai.errors.GenAiIOException; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import okhttp3.Headers; +import okhttp3.MediaType; +import okhttp3.ResponseBody; -// TODO(b/369384123): Change the replay API response to use the ReplayFile. /** Provides a simulated HTTP response from a replay file. */ +@InternalApi @ExcludeFromGeneratedCoverageReport -final class ReplayApiResponse extends ApiResponse { +public final class ReplayApiResponse extends ApiResponse { - private final HttpEntity entity; - private final StatusLine statusLine; - private final Header[] headers; + private final ResponseBody body; + private final int statusCode; + private final Headers headers; + private final ArrayNode bodySegments; - public ReplayApiResponse(HttpEntity entity, StatusLine statusLine, Header[] headers) { - this.entity = entity; - this.statusLine = statusLine; + public ReplayApiResponse( + ArrayNode bodySegments, int statusCode, Headers headers, boolean isStream) { + this.bodySegments = bodySegments; + this.statusCode = statusCode; this.headers = headers; + if (bodySegments.size() == 0) { + this.body = ResponseBody.create(MediaType.parse("application/json"), ""); + } else if (isStream || bodySegments.size() > 1) { + // For streaming response + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + byte[] dataPrefix = "data: ".getBytes(StandardCharsets.UTF_8); + byte[] doubleNewline = "\n\n".getBytes(StandardCharsets.UTF_8); + for (JsonNode segment : bodySegments) { + outputStream.write(dataPrefix); + outputStream.write(JsonSerializable.objectMapper.writeValueAsBytes(segment)); + outputStream.write(doubleNewline); + } + this.body = + ResponseBody.create(outputStream.toByteArray(), MediaType.parse("application/json")); + } catch (IOException e) { + throw new GenAiIOException("Failed to convert body segments to a JSON string.", e); + } + } else { + // For unary response + this.body = + ResponseBody.create( + JsonSerializable.toJsonString(bodySegments.get(0)), + MediaType.parse("application/json")); + } } @Override - public HttpEntity getEntity() { - return this.entity; + public ResponseBody getBody() { + ApiException.throwFromErrorNode(bodySegments, statusCode); + return this.body; } @Override - public Header[] getHeaders() { return this.headers;} + public Headers getHeaders() { + return this.headers; + } + + public int getStatusCode() { + return this.statusCode; + } @Override public void close() {} diff --git a/src/main/java/com/google/genai/ResponseStream.java b/src/main/java/com/google/genai/ResponseStream.java index 7edff77c575..9065308abbe 100644 --- a/src/main/java/com/google/genai/ResponseStream.java +++ b/src/main/java/com/google/genai/ResponseStream.java @@ -1,5 +1,5 @@ /* - * Copyright 2025 Google LLC + * Copyright 2026 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,9 @@ package com.google.genai; 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.ApiException; import com.google.genai.errors.GenAiIOException; import java.io.BufferedReader; import java.io.IOException; @@ -29,9 +31,10 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.logging.Logger; import java.util.NoSuchElementException; -import org.apache.http.HttpEntity; +import java.util.logging.Logger; +import okhttp3.Headers; +import org.jspecify.annotations.Nullable; /** An iterable of datatype objects. */ public class ResponseStream implements Iterable, AutoCloseable { @@ -49,20 +52,34 @@ class ResponseStreamIterator implements Iterator { private final Class clazz; private final Object obj; private final Method converter; + private final boolean needsRootObject; + private final Headers responseHeaders; private String nextJson; private boolean consumed = false; ResponseStreamIterator( - Class clazz, BufferedReader reader, Object obj, String converterName) { + Class clazz, + BufferedReader reader, + Object obj, + String converterName, + boolean needsRootObject, + Headers responseHeaders) { this.reader = reader; this.clazz = clazz; this.nextJson = readNextJson(); this.obj = obj; + this.needsRootObject = needsRootObject; + this.responseHeaders = responseHeaders; try { - this.converter = - obj.getClass() - .getDeclaredMethod( - converterName, ApiClient.class, 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); } @@ -100,33 +117,87 @@ public T next() { nextJson = readNextJson(); try { JsonNode currentJsonNode = JsonSerializable.stringToJsonNode(currentJson); - currentJsonNode = (JsonNode) converter.invoke(obj, null, currentJsonNode, null); + + if (currentJsonNode.isObject() && currentJsonNode.has("error")) { + int extractedCode = 500; + JsonNode errorNode = currentJsonNode.get("error"); + if (errorNode.has("code") && errorNode.get("code").isInt()) { + extractedCode = errorNode.get("code").asInt(); + } + ArrayNode arrayNode = JsonSerializable.objectMapper.createArrayNode(); + arrayNode.add(currentJsonNode); + ApiException.throwFromErrorNode(arrayNode, extractedCode); + } + + if (responseHeaders != null && currentJsonNode.isObject()) { + ObjectNode rootNode = (ObjectNode) currentJsonNode; + ObjectNode headersNode = JsonSerializable.objectMapper.createObjectNode(); + for (String headerName : responseHeaders.names()) { + headersNode.put(headerName, responseHeaders.get(headerName)); + } + ObjectNode sdkHttpResponseNode = JsonSerializable.objectMapper.createObjectNode(); + sdkHttpResponseNode.set("headers", headersNode); + rootNode.set("sdkHttpResponse", sdkHttpResponseNode); + currentJsonNode = rootNode; + } + if (needsRootObject) { + currentJsonNode = + (JsonNode) converter.invoke(obj, currentJsonNode, null, currentJsonNode); + } else { + currentJsonNode = (JsonNode) converter.invoke(obj, currentJsonNode, null); + } + + T response = JsonSerializable.fromJsonNode(currentJsonNode, clazz); if (recordingHistory) { - T response = JsonSerializable.fromJsonNode(currentJsonNode, clazz); history.add(response); - return response; } - return JsonSerializable.fromJsonNode(currentJsonNode, clazz); + return response; } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("Failed to convert JSON object " + currentJson, e); } } - private String readNextJson() { + private @Nullable String readNextJson() { // Streaming API returns in the following format: // data: {contents: ...} // \n // data: {contents: ...} // \n // ... + List dataBuffer = new ArrayList<>(); try { - String line = reader.readLine(); - if (line == null) { - return null; - } else if (line.length() == 0) { - return readNextJson(); - } else { - return line.substring("data: ".length()); + while (true) { + String line = reader.readLine(); + if (line == null) { + if (!dataBuffer.isEmpty()) { + return String.join("\n", dataBuffer); + } + return null; + } + if (line.isEmpty()) { + if (!dataBuffer.isEmpty()) { + // Handle multi-line SSE data + return String.join("\n", dataBuffer); + } + continue; + } + if (line.startsWith(":")) { + continue; + } + int colonIndex = line.indexOf(':'); + String fieldname = line; + String value = ""; + if (colonIndex != -1) { + fieldname = line.substring(0, colonIndex); + value = line.substring(colonIndex + 1); + if (value.startsWith(" ")) { + value = value.substring(1); + } + } + + if (fieldname.equals("data")) { + dataBuffer.add(value); + } } } catch (IOException e) { throw new GenAiIOException("Failed to read next JSON object from the stream", e); @@ -139,15 +210,25 @@ private String readNextJson() { private final BufferedReader reader; public ResponseStream(Class clazz, ApiResponse response, Object obj, String converterName) { - HttpEntity entity = response.getEntity(); - InputStream responseStream; - try { - responseStream = entity.getContent(); - } catch (IOException e) { - throw new GenAiIOException("Failed to read HTTP response.", e); - } + this(clazz, response, obj, converterName, false, false); + } + + ResponseStream( + Class clazz, + ApiResponse response, + Object obj, + String converterName, + boolean needsRootObject, + boolean canReturnHttpHeaders) { + InputStream responseStream = response.getBody().byteStream(); this.reader = new BufferedReader(new InputStreamReader(responseStream, StandardCharsets.UTF_8)); - this.iterator = new ResponseStreamIterator(clazz, this.reader, obj, converterName); + Headers headers = null; + if (canReturnHttpHeaders) { + headers = response.getHeaders(); + } + this.iterator = + new ResponseStreamIterator( + clazz, this.reader, obj, converterName, needsRootObject, headers); 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/Tokens.java b/src/main/java/com/google/genai/Tokens.java new file mode 100644 index 00000000000..116c2cadfa2 --- /dev/null +++ b/src/main/java/com/google/genai/Tokens.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. + */ + +package com.google.genai; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.collect.ImmutableList; +import com.google.genai.Common.BuiltRequest; +import com.google.genai.errors.GenAiIOException; +import com.google.genai.types.AuthToken; +import com.google.genai.types.CreateAuthTokenConfig; +import com.google.genai.types.CreateAuthTokenParameters; +import com.google.genai.types.HttpOptions; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import okhttp3.ResponseBody; + +/** Provides methods for managing the ephemeral auth tokens. The tokens module is experimental. */ +public class Tokens { + + private final ApiClient apiClient; + + Tokens(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ + static String getFieldMasks(ObjectNode setup) { + List fields = new ArrayList<>(); + + Iterator> fieldsIterator = setup.fields(); + while (fieldsIterator.hasNext()) { + Map.Entry entry = fieldsIterator.next(); + String key = entry.getKey(); + JsonNode value = entry.getValue(); + + // 2nd layer, recursively get field masks + if (value.isObject() && value.size() > 0) { + Iterator subKeys = value.fieldNames(); + while (subKeys.hasNext()) { + String kk = subKeys.next(); + fields.add(key + "." + kk); + } + } else { + fields.add(key); // 1st layer + } + } + return String.join(",", fields); + } + + /** + * Converts the bidi setup in the config to the token setup. + * + * @param body The request body. + * @param config The config of the create auth token request. + * @return The modified request body. + */ + ObjectNode convertBidiSetupToTokenSetup(ObjectNode body, CreateAuthTokenConfig config) { + ObjectNode transformedBody = body.deepCopy(); + ObjectNode setupForMaskGeneration = null; + JsonNode bidiVal = body.get("bidiGenerateContentSetup"); + + // Handle extraction of the inner 'setup' + // We assume the value in the map is compatible with ObjectNode per the requirements + if (bidiVal != null && bidiVal.get("setup") != null) { + JsonNode innerSetup = bidiVal.get("setup"); + if (innerSetup != null) { + // Valid inner setup found. + transformedBody.put("bidiGenerateContentSetup", innerSetup); + setupForMaskGeneration = (ObjectNode) innerSetup; + } + } else { + transformedBody.remove("bidiGenerateContentSetup"); + } + + // Extract Pre-existing field mask + JsonNode preExistingFieldMask = body.get("fieldMask"); + List preExistingFieldMaskList = new ArrayList<>(); + if (preExistingFieldMask != null && preExistingFieldMask.isArray()) { + for (JsonNode element : preExistingFieldMask) { + if (element.isTextual()) { + preExistingFieldMaskList.add(element.asText()); + } + } + } + + // Handle mask generation setup. + if (setupForMaskGeneration != null) { + String generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + + boolean configLockExists = config != null && config.lockAdditionalFields().isPresent(); + boolean preExistingValid = + preExistingFieldMaskList != null && !preExistingFieldMaskList.isEmpty(); + + if (configLockExists + && config.lockAdditionalFields().isPresent() + && config.lockAdditionalFields().get().isEmpty()) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from bidi setup. + if (generatedMaskFromBidi != null && !generatedMaskFromBidi.isEmpty()) { + transformedBody.put("fieldMask", generatedMaskFromBidi); + } else { + transformedBody.remove("fieldMask"); + } + + } else if (configLockExists + && config.lockAdditionalFields().isPresent() + && !config.lockAdditionalFields().get().isEmpty() + && preExistingValid) { + // Case 2: Lock fields from bidi setup + additional fields. + + List generationConfigFields = + ImmutableList.of( + "temperature", + "topK", + "top_k", + "topP", + "top_p", + "maxOutputTokens", + "max_output_tokens", + "responseModalities", + "response_modalities", + "seed", + "speechConfig", + "speech_config"); + + List mappedFieldsFromPreExisting = new ArrayList<>(); + for (String field : preExistingFieldMaskList) { + if (generationConfigFields.contains(field)) { + mappedFieldsFromPreExisting.add("generationConfig." + field); + } else { + mappedFieldsFromPreExisting.add(field); + } + } + + List finalMaskParts = new ArrayList<>(); + if (generatedMaskFromBidi != null && !generatedMaskFromBidi.isEmpty()) { + finalMaskParts.add(generatedMaskFromBidi); + } + finalMaskParts.addAll(mappedFieldsFromPreExisting); + + if (!finalMaskParts.isEmpty()) { + transformedBody.put("fieldMask", String.join(",", finalMaskParts)); + } else { + transformedBody.remove("fieldMask"); + } + + } else { + // Case 3: "Lock all fields" + transformedBody.remove("fieldMask"); + } + } else { + // No valid `bidiGenerateContentSetup` found. + if (preExistingFieldMaskList != null && !preExistingFieldMaskList.isEmpty()) { + transformedBody.put("fieldMask", String.join(",", preExistingFieldMaskList)); + } else { + transformedBody.remove("fieldMask"); + } + } + return transformedBody; + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForCreate(CreateAuthTokenConfig config) { + + CreateAuthTokenParameters.Builder parameterBuilder = CreateAuthTokenParameters.builder(); + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + TokensConverters tokensConverters = new TokensConverters(apiClient); + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in the Gemini Developer client."); + } else { + body = tokensConverters.createAuthTokenParametersToMldev(this.apiClient, parameterNode, null); + if (body.get("_url") != null) { + path = Common.formatMap("auth_tokens", body.get("_url")); + } else { + path = "auth_tokens"; + } + } + 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(); + } + + ObjectNode transformedBody = convertBidiSetupToTokenSetup(body, config); + transformedBody.remove("config"); + return new BuiltRequest( + path, JsonSerializable.toJsonString(transformedBody), requestHttpOptions); + } + + /** A shared processResponse function for both sync and async methods. */ + AuthToken processResponseForCreate(ApiResponse response, CreateAuthTokenConfig 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, AuthToken.class); + } + + /** + * Creates an ephemeral auth token resource. + * + * @param config A {@link CreateAuthTokenConfig} for configuring the create request. + * @return A {@link AuthToken} object that contains the info of the created resource. + */ + public AuthToken create(CreateAuthTokenConfig config) { + BuiltRequest builtRequest = buildRequestForCreate(config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path, builtRequest.body, builtRequest.httpOptions)) { + return processResponseForCreate(response, config); + } + } +} diff --git a/src/main/java/com/google/genai/TokensConverters.java b/src/main/java/com/google/genai/TokensConverters.java index 9c5cc5dfd10..f7e021f1e52 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; @@ -31,315 +32,201 @@ public TokensConverters(ApiClient apiClient) { } @ExcludeFromGeneratedCoverageReport - ObjectNode prebuiltVoiceConfigToMldev( - ApiClient apiClient, 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 prebuiltVoiceConfigToVertex( - ApiClient apiClient, 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(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"prebuiltVoiceConfig"}, - prebuiltVoiceConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"})), - toObject)); + ObjectNode audioTranscriptionConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"languageCodes"}))) { + throw new IllegalArgumentException( + "languageCodes parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode voiceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"}) != null) { + ObjectNode authConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"apiKey"}) != null) { Common.setValueByPath( toObject, - new String[] {"prebuiltVoiceConfig"}, - prebuiltVoiceConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"prebuiltVoiceConfig"})), - toObject)); + new String[] {"apiKey"}, + Common.getValueByPath(fromObject, new String[] {"apiKey"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode speakerVoiceConfigToMldev( - ApiClient apiClient, 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[] {"apiKeyConfig"}))) { + throw new IllegalArgumentException( + "apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"authType"}))) { + throw new IllegalArgumentException( + "authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode speakerVoiceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"speaker"}))) { - throw new IllegalArgumentException("speaker parameter is not supported in Vertex AI."); + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"googleServiceAccountConfig"}))) { + throw new IllegalArgumentException( + "googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent" + + " Platform mode, not in Gemini Developer API mode."); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"voiceConfig"}))) { - throw new IllegalArgumentException("voiceConfig parameter is not supported in Vertex AI."); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"httpBasicAuthConfig"}))) { + throw new IllegalArgumentException( + "httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode multiSpeakerVoiceConfigToMldev( - 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(); - - for (JsonNode item : keyArray) { - result.add( - speakerVoiceConfigToMldev(apiClient, JsonSerializable.toJsonNode(item), toObject)); - } - Common.setValueByPath(toObject, new String[] {"speakerVoiceConfigs"}, result); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"oauthConfig"}))) { + throw new IllegalArgumentException( + "oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode multiSpeakerVoiceConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"speakerVoiceConfigs"}))) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"oidcConfig"}))) { throw new IllegalArgumentException( - "speakerVoiceConfigs parameter is not supported in Vertex AI."); + "oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode speechConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { + ObjectNode blobToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"data"}) != null) { Common.setValueByPath( toObject, - new String[] {"voiceConfig"}, - voiceConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); + new String[] {"data"}, + Common.getValueByPath(fromObject, new String[] {"data"})); } - if (Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"multiSpeakerVoiceConfig"}, - multiSpeakerVoiceConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"displayName"}))) { + throw new IllegalArgumentException( + "displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - 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 speechConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"voiceConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"voiceConfig"}, - voiceConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"voiceConfig"})), - toObject)); - } + 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.isZero( - Common.getValueByPath(fromObject, new String[] {"multiSpeakerVoiceConfig"}))) { - throw new IllegalArgumentException( - "multiSpeakerVoiceConfig parameter is not supported in Vertex AI."); + for (JsonNode item : keyArray) { + result.add(partToMldev(JsonSerializable.toJsonNode(item), toObject)); + } + Common.setValueByPath(toObject, new String[] {"parts"}, result); } - if (Common.getValueByPath(fromObject, new String[] {"languageCode"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"role"}) != null) { Common.setValueByPath( toObject, - new String[] {"languageCode"}, - Common.getValueByPath(fromObject, new String[] {"languageCode"})); + new String[] {"role"}, + Common.getValueByPath(fromObject, new String[] {"role"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToMldev( + ObjectNode createAuthTokenConfigToMldev( ApiClient apiClient, 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"})); - } + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"expireTime"}) != null) { Common.setValueByPath( - toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + parentObject, + new String[] {"expireTime"}, + Common.getValueByPath(fromObject, new String[] {"expireTime"})); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"newSessionExpireTime"}) != null) { Common.setValueByPath( - toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + parentObject, + new String[] {"newSessionExpireTime"}, + Common.getValueByPath(fromObject, new String[] {"newSessionExpireTime"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode videoMetadataToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"fps"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"uses"}) != null) { Common.setValueByPath( - toObject, new String[] {"fps"}, Common.getValueByPath(fromObject, new String[] {"fps"})); + parentObject, + new String[] {"uses"}, + Common.getValueByPath(fromObject, new String[] {"uses"})); } - if (Common.getValueByPath(fromObject, new String[] {"endOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"liveConnectConstraints"}) != null) { Common.setValueByPath( - toObject, - new String[] {"endOffset"}, - Common.getValueByPath(fromObject, new String[] {"endOffset"})); + parentObject, + new String[] {"bidiGenerateContentSetup"}, + liveConnectConstraintsToMldev( + apiClient, + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"liveConnectConstraints"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"startOffset"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"lockAdditionalFields"}) != null) { Common.setValueByPath( - toObject, - new String[] {"startOffset"}, - Common.getValueByPath(fromObject, new String[] {"startOffset"})); + parentObject, + new String[] {"fieldMask"}, + Common.getValueByPath(fromObject, new String[] {"lockAdditionalFields"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode blobToMldev(ApiClient apiClient, 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, - new String[] {"data"}, - Common.getValueByPath(fromObject, new String[] {"data"})); - } - - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + ObjectNode createAuthTokenParametersToMldev( + ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"config"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"config"}, + createAuthTokenConfigToMldev( + apiClient, + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"config"})), + toObject)); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode blobToVertex(ApiClient apiClient, 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) { - Common.setValueByPath( - toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + ObjectNode createAuthTokenParametersToVertex(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"config"}))) { + throw new IllegalArgumentException( + "config parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + 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."); + throw new IllegalArgumentException( + "displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { @@ -360,1317 +247,100 @@ ObjectNode fileDataToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode } @ExcludeFromGeneratedCoverageReport - ObjectNode fileDataToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"displayName"}) != null) { + ObjectNode functionCallToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"id"}) != null) { Common.setValueByPath( - toObject, - new String[] {"displayName"}, - Common.getValueByPath(fromObject, new String[] {"displayName"})); + toObject, new String[] {"id"}, Common.getValueByPath(fromObject, new String[] {"id"})); } - if (Common.getValueByPath(fromObject, new String[] {"fileUri"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"args"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileUri"}, - Common.getValueByPath(fromObject, new String[] {"fileUri"})); + new String[] {"args"}, + Common.getValueByPath(fromObject, new String[] {"args"})); } - if (Common.getValueByPath(fromObject, new String[] {"mimeType"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"name"}) != null) { Common.setValueByPath( toObject, - new String[] {"mimeType"}, - Common.getValueByPath(fromObject, new String[] {"mimeType"})); + new String[] {"name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode partToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"videoMetadata"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"partialArgs"}))) { + throw new IllegalArgumentException( + "partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); } - 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[] {"willContinue"}))) { + throw new IllegalArgumentException( + "willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"inlineData"}, - blobToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode googleMapsToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"authConfig"}) != null) { Common.setValueByPath( toObject, - new String[] {"fileData"}, - fileDataToMldev( - apiClient, + new String[] {"authConfig"}, + authConfigToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"fileData"})), + Common.getValueByPath(fromObject, new String[] {"authConfig"})), 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) { + if (Common.getValueByPath(fromObject, new String[] {"enableWidget"}) != null) { Common.setValueByPath( toObject, - new String[] {"executableCode"}, - Common.getValueByPath(fromObject, new String[] {"executableCode"})); + new String[] {"enableWidget"}, + Common.getValueByPath(fromObject, new String[] {"enableWidget"})); } - if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"functionCall"}, - Common.getValueByPath(fromObject, new String[] {"functionCall"})); - } + return toObject; + } - if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { + @ExcludeFromGeneratedCoverageReport + ObjectNode googleSearchToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"searchTypes"}) != 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 partToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"videoMetadata"}, - videoMetadataToVertex( - apiClient, - 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"}, - blobToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"inlineData"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"fileData"}, - fileDataToVertex( - apiClient, - 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 contentToMldev(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(); - - for (JsonNode item : keyArray) { - result.add(partToMldev(apiClient, 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 contentToVertex(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(); - - for (JsonNode item : keyArray) { - result.add(partToVertex(apiClient, 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 functionDeclarationToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"behavior"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"behavior"}, - Common.getValueByPath(fromObject, new String[] {"behavior"})); - } - - 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[] {"response"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode functionDeclarationToVertex( - 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[] {"response"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"response"}, - Common.getValueByPath(fromObject, new String[] {"response"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToMldev(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) { - Common.setValueByPath( - toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode intervalToVertex(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) { - Common.setValueByPath( - toObject, - new String[] {"endTime"}, - Common.getValueByPath(fromObject, new String[] {"endTime"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"timeRangeFilter"}, - intervalToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"timeRangeFilter"}, - intervalToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToMldev( - 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) { - Common.setValueByPath( - toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode dynamicRetrievalConfigToVertex( - 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) { - Common.setValueByPath( - toObject, - new String[] {"dynamicThreshold"}, - Common.getValueByPath(fromObject, new String[] {"dynamicThreshold"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleSearchRetrievalToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"dynamicRetrievalConfig"}, - dynamicRetrievalConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"dynamicRetrievalConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode enterpriseWebSearchToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode enterpriseWebSearchToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode apiKeyConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyString"}))) { - throw new IllegalArgumentException("apiKeyString parameter is not supported in Gemini API."); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode apiKeyConfigToVertex( - ApiClient apiClient, 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 authConfigToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}))) { - throw new IllegalArgumentException("apiKeyConfig parameter is not supported in Gemini API."); - } - - 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 authConfigToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"apiKeyConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"apiKeyConfig"}, - apiKeyConfigToVertex( - apiClient, - 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 googleMapsToMldev(ApiClient apiClient, 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."); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode googleMapsToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"authConfig"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"authConfig"}, - authConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"authConfig"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode urlContextToVertex(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolToMldev(ApiClient apiClient, 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(apiClient, 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) { - Common.setValueByPath( - toObject, - new String[] {"googleSearch"}, - googleSearchToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - 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) { - Common.setValueByPath( - toObject, - new String[] {"urlContext"}, - urlContextToMldev( - apiClient, - 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"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode toolToVertex(ApiClient apiClient, 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(apiClient, 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( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearch"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleSearchRetrieval"}, - googleSearchRetrievalToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"enterpriseWebSearch"}, - enterpriseWebSearchToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"googleMaps"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"googleMaps"}, - googleMapsToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"googleMaps"})), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"urlContext"}, - urlContextToVertex( - apiClient, - 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"})); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode sessionResumptionConfigToMldev( - ApiClient apiClient, 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.isZero(Common.getValueByPath(fromObject, new String[] {"transparent"}))) { - throw new IllegalArgumentException("transparent parameter is not supported in Gemini API."); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode sessionResumptionConfigToVertex( - ApiClient apiClient, 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 audioTranscriptionConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode audioTranscriptionConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode automaticActivityDetectionToMldev( - ApiClient apiClient, 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 automaticActivityDetectionToVertex( - ApiClient apiClient, 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 realtimeInputConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"automaticActivityDetection"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"automaticActivityDetection"}, - automaticActivityDetectionToMldev( - apiClient, - 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 realtimeInputConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (Common.getValueByPath(fromObject, new String[] {"automaticActivityDetection"}) != null) { - Common.setValueByPath( - toObject, - new String[] {"automaticActivityDetection"}, - automaticActivityDetectionToVertex( - apiClient, - 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 slidingWindowToMldev( - ApiClient apiClient, 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 slidingWindowToVertex( - ApiClient apiClient, 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 contextWindowCompressionConfigToMldev( - ApiClient apiClient, 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"}, - slidingWindowToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"slidingWindow"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode contextWindowCompressionConfigToVertex( - ApiClient apiClient, 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( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"slidingWindow"})), - toObject)); - } - - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode proactivityConfigToMldev( - ApiClient apiClient, 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 proactivityConfigToVertex( - ApiClient apiClient, 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 liveConnectConfigToMldev( - ApiClient apiClient, 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"}, - speechConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tLiveSpeechConfig( - this.apiClient, - 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"}, - contentToMldev( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tContent( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), - toObject)); - } - - if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { - ArrayNode keyArray = - (ArrayNode) - Transformers.tTools( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"tools"})); - ObjectMapper objectMapper = new ObjectMapper(); - ArrayNode result = objectMapper.createArrayNode(); - - for (JsonNode item : keyArray) { - result.add( - toolToMldev( - apiClient, - JsonSerializable.toJsonNode(Transformers.tTool(this.apiClient, 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"}, - sessionResumptionConfigToMldev( - apiClient, - 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( - apiClient, - 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( - apiClient, - 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( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})), - toObject)); + toObject, + new String[] {"searchTypes"}, + Common.getValueByPath(fromObject, new String[] {"searchTypes"})); } - if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { - Common.setValueByPath( - parentObject, - new String[] {"setup", "contextWindowCompression"}, - contextWindowCompressionConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})), - toObject)); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"blockingConfidence"}))) { + throw new IllegalArgumentException( + "blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); } - if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"excludeDomains"}))) { + throw new IllegalArgumentException( + "excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"setup", "proactivity"}, - proactivityConfigToMldev( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"proactivity"})), - toObject)); + toObject, + new String[] {"timeRangeFilter"}, + Common.getValueByPath(fromObject, new String[] {"timeRangeFilter"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode liveConnectConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode liveConnectConfigToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"responseModalities"}) != null) { Common.setValueByPath( @@ -1725,13 +395,15 @@ ObjectNode liveConnectConfigToVertex( Common.setValueByPath( parentObject, new String[] {"setup", "generationConfig", "speechConfig"}, - speechConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Transformers.tLiveSpeechConfig( - this.apiClient, - Common.getValueByPath(fromObject, new String[] {"speechConfig"}))), - toObject)); + Transformers.tLiveSpeechConfig( + Common.getValueByPath(fromObject, new String[] {"speechConfig"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"thinkingConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"setup", "generationConfig", "thinkingConfig"}, + Common.getValueByPath(fromObject, new String[] {"thinkingConfig"})); } if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { @@ -1745,11 +417,9 @@ ObjectNode liveConnectConfigToVertex( Common.setValueByPath( parentObject, new String[] {"setup", "systemInstruction"}, - contentToVertex( - apiClient, + contentToMldev( JsonSerializable.toJsonNode( Transformers.tContent( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"systemInstruction"}))), toObject)); } @@ -1757,17 +427,12 @@ ObjectNode liveConnectConfigToVertex( if (Common.getValueByPath(fromObject, new String[] {"tools"}) != null) { ArrayNode keyArray = (ArrayNode) - Transformers.tTools( - this.apiClient, Common.getValueByPath(fromObject, new String[] {"tools"})); + Transformers.tTools(Common.getValueByPath(fromObject, new String[] {"tools"})); ObjectMapper objectMapper = new ObjectMapper(); ArrayNode result = objectMapper.createArrayNode(); for (JsonNode item : keyArray) { - result.add( - toolToVertex( - apiClient, - JsonSerializable.toJsonNode(Transformers.tTool(this.apiClient, item)), - toObject)); + result.add(toolToMldev(JsonSerializable.toJsonNode(Transformers.tTool(item)), toObject)); } Common.setValueByPath(parentObject, new String[] {"setup", "tools"}, result); } @@ -1776,8 +441,7 @@ ObjectNode liveConnectConfigToVertex( Common.setValueByPath( parentObject, new String[] {"setup", "sessionResumption"}, - sessionResumptionConfigToVertex( - apiClient, + sessionResumptionConfigToMldev( JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"sessionResumption"})), toObject)); @@ -1787,8 +451,7 @@ ObjectNode liveConnectConfigToVertex( Common.setValueByPath( parentObject, new String[] {"setup", "inputAudioTranscription"}, - audioTranscriptionConfigToVertex( - apiClient, + audioTranscriptionConfigToMldev( JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"inputAudioTranscription"})), toObject)); @@ -1798,8 +461,7 @@ ObjectNode liveConnectConfigToVertex( Common.setValueByPath( parentObject, new String[] {"setup", "outputAudioTranscription"}, - audioTranscriptionConfigToVertex( - apiClient, + audioTranscriptionConfigToMldev( JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"outputAudioTranscription"})), toObject)); @@ -1809,33 +471,53 @@ ObjectNode liveConnectConfigToVertex( Common.setValueByPath( parentObject, new String[] {"setup", "realtimeInputConfig"}, - realtimeInputConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"realtimeInputConfig"})); } if (Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"}) != null) { Common.setValueByPath( parentObject, new String[] {"setup", "contextWindowCompression"}, - contextWindowCompressionConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"contextWindowCompression"})); } if (Common.getValueByPath(fromObject, new String[] {"proactivity"}) != null) { Common.setValueByPath( parentObject, new String[] {"setup", "proactivity"}, - proactivityConfigToVertex( - apiClient, - JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"proactivity"})), - toObject)); + Common.getValueByPath(fromObject, new String[] {"proactivity"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"explicitVadSignal"}))) { + throw new IllegalArgumentException( + "explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"avatarConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"setup", "avatarConfig"}, + Common.getValueByPath(fromObject, new String[] {"avatarConfig"})); + } + + 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[] {"setup", "safetySettings"}, result); + } + + if (Common.getValueByPath(fromObject, new String[] {"streamTranslationConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"setup", "generationConfig", "streamTranslationConfig"}, + Common.getValueByPath(fromObject, new String[] {"streamTranslationConfig"})); } return toObject; @@ -1844,7 +526,7 @@ ObjectNode liveConnectConfigToVertex( @ExcludeFromGeneratedCoverageReport ObjectNode liveConnectConstraintsToMldev( ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); if (Common.getValueByPath(fromObject, new String[] {"model"}) != null) { Common.setValueByPath( toObject, @@ -1858,7 +540,6 @@ ObjectNode liveConnectConstraintsToMldev( toObject, new String[] {"config"}, liveConnectConfigToMldev( - apiClient, JsonSerializable.toJsonNode( Common.getValueByPath(fromObject, new String[] {"config"})), toObject)); @@ -1868,126 +549,252 @@ ObjectNode liveConnectConstraintsToMldev( } @ExcludeFromGeneratedCoverageReport - ObjectNode liveConnectConstraintsToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"model"}))) { - throw new IllegalArgumentException("model parameter is not supported in Vertex AI."); + ObjectNode partToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"mediaResolution"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"config"}))) { - throw new IllegalArgumentException("config parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"codeExecutionResult"}, + Common.getValueByPath(fromObject, new String[] {"codeExecutionResult"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode createAuthTokenConfigToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + 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[] {"expireTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"fileData"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"expireTime"}, - Common.getValueByPath(fromObject, new String[] {"expireTime"})); + toObject, + new String[] {"fileData"}, + fileDataToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"fileData"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"newSessionExpireTime"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionCall"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"newSessionExpireTime"}, - Common.getValueByPath(fromObject, new String[] {"newSessionExpireTime"})); + toObject, + new String[] {"functionCall"}, + functionCallToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"functionCall"})), + toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"uses"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"functionResponse"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"uses"}, - Common.getValueByPath(fromObject, new String[] {"uses"})); + toObject, + new String[] {"functionResponse"}, + Common.getValueByPath(fromObject, new String[] {"functionResponse"})); } - if (Common.getValueByPath(fromObject, new String[] {"liveConnectConstraints"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"inlineData"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"bidiGenerateContentSetup"}, - liveConnectConstraintsToMldev( - apiClient, + toObject, + new String[] {"inlineData"}, + blobToMldev( JsonSerializable.toJsonNode( - Common.getValueByPath(fromObject, new String[] {"liveConnectConstraints"})), + Common.getValueByPath(fromObject, new String[] {"inlineData"})), toObject)); } - if (Common.getValueByPath(fromObject, new String[] {"lockAdditionalFields"}) != null) { + if (Common.getValueByPath(fromObject, new String[] {"text"}) != null) { Common.setValueByPath( - parentObject, - new String[] {"fieldMask"}, - Common.getValueByPath(fromObject, new String[] {"lockAdditionalFields"})); + toObject, + new String[] {"text"}, + Common.getValueByPath(fromObject, new String[] {"text"})); } - return toObject; - } - - @ExcludeFromGeneratedCoverageReport - ObjectNode createAuthTokenConfigToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + 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[] {"expireTime"}))) { - throw new IllegalArgumentException("expireTime parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"thoughtSignature"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"thoughtSignature"}, + Common.getValueByPath(fromObject, new String[] {"thoughtSignature"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"newSessionExpireTime"}))) { - throw new IllegalArgumentException( - "newSessionExpireTime parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"videoMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"videoMetadata"}, + Common.getValueByPath(fromObject, new String[] {"videoMetadata"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"uses"}))) { - throw new IllegalArgumentException("uses parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"toolCall"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"toolCall"}, + Common.getValueByPath(fromObject, new String[] {"toolCall"})); } - if (!Common.isZero( - Common.getValueByPath(fromObject, new String[] {"liveConnectConstraints"}))) { - throw new IllegalArgumentException( - "liveConnectConstraints parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"toolResponse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"toolResponse"}, + Common.getValueByPath(fromObject, new String[] {"toolResponse"})); } - if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"lockAdditionalFields"}))) { - throw new IllegalArgumentException( - "lockAdditionalFields parameter is not supported in Vertex AI."); + if (Common.getValueByPath(fromObject, new String[] {"partMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"partMetadata"}, + Common.getValueByPath(fromObject, new String[] {"partMetadata"})); } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode createAuthTokenParametersToMldev( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode safetySettingToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"category"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"category"}, + Common.getValueByPath(fromObject, new String[] {"category"})); + } - return toObject; - } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"method"}))) { + throw new IllegalArgumentException( + "method parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } - @ExcludeFromGeneratedCoverageReport - ObjectNode createAuthTokenParametersToVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"threshold"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"threshold"}, + Common.getValueByPath(fromObject, new String[] {"threshold"})); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode authTokenFromMldev(ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode sessionResumptionConfigToMldev(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.isZero(Common.getValueByPath(fromObject, new String[] {"transparent"}))) { + throw new IllegalArgumentException( + "transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } return toObject; } @ExcludeFromGeneratedCoverageReport - ObjectNode authTokenFromVertex( - ApiClient apiClient, JsonNode fromObject, ObjectNode parentObject) { - ObjectNode toObject = JsonSerializable.objectMapper.createObjectNode(); + ObjectNode toolToMldev(JsonNode fromObject, ObjectNode parentObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"retrieval"}))) { + throw new IllegalArgumentException( + "retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"computerUse"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"computerUse"}, + Common.getValueByPath(fromObject, new String[] {"computerUse"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"fileSearch"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"fileSearch"}, + Common.getValueByPath(fromObject, new String[] {"fileSearch"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"googleSearch"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"googleSearch"}, + googleSearchToMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"googleSearch"})), + 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)); + } + + if (Common.getValueByPath(fromObject, new String[] {"codeExecution"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"codeExecution"}, + Common.getValueByPath(fromObject, new String[] {"codeExecution"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"enterpriseWebSearch"}))) { + throw new IllegalArgumentException( + "enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"functionDeclarations"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"functionDeclarations"}, + Common.getValueByPath(fromObject, new String[] {"functionDeclarations"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"googleSearchRetrieval"}, + Common.getValueByPath(fromObject, new String[] {"googleSearchRetrieval"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"parallelAiSearch"}))) { + throw new IllegalArgumentException( + "parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"urlContext"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"urlContext"}, + Common.getValueByPath(fromObject, new String[] {"urlContext"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"mcpServers"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mcpServers"}, + Common.getValueByPath(fromObject, new String[] {"mcpServers"})); + } return toObject; } diff --git a/src/main/java/com/google/genai/Transformers.java b/src/main/java/com/google/genai/Transformers.java index f2521ab7b62..75cd95be605 100644 --- a/src/main/java/com/google/genai/Transformers.java +++ b/src/main/java/com/google/genai/Transformers.java @@ -20,21 +20,25 @@ import com.fasterxml.jackson.core.type.TypeReference; 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.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; +import com.google.api.core.InternalApi; import com.google.common.collect.ImmutableList; import com.google.genai.types.Blob; import com.google.genai.types.Content; import com.google.genai.types.File; import com.google.genai.types.FunctionDeclaration; import com.google.genai.types.GeneratedVideo; +import com.google.genai.types.JobState; import com.google.genai.types.Part; import com.google.genai.types.PrebuiltVoiceConfig; import com.google.genai.types.Schema; import com.google.genai.types.SpeechConfig; import com.google.genai.types.Tool; +import com.google.genai.types.UnifiedMetric; import com.google.genai.types.Video; import com.google.genai.types.VoiceConfig; import java.lang.reflect.Method; @@ -46,7 +50,8 @@ import org.jspecify.annotations.Nullable; /** Transformers for GenAI SDK. */ -final class Transformers { +@InternalApi +public final class Transformers { private static final Logger logger = Logger.getLogger(Transformers.class.getName()); private Transformers() {} @@ -61,7 +66,7 @@ private Transformers() {} public static String tModel(ApiClient apiClient, Object origin) { String model; if (origin == null) { - return null; + throw new IllegalArgumentException("model is required."); } else if (origin instanceof String) { model = (String) origin; } else if (origin instanceof JsonNode) { @@ -70,6 +75,12 @@ public static String tModel(ApiClient apiClient, Object origin) { } else { throw new IllegalArgumentException("Unsupported model type: " + origin.getClass()); } + if (model.isEmpty()) { + throw new IllegalArgumentException("model is required."); + } + if (model.contains("..") || model.contains("?") || model.contains("&")) { + throw new IllegalArgumentException("invalid model parameter."); + } if (apiClient.vertexAI()) { if (model.startsWith("publishers/") || model.startsWith("projects/") @@ -120,7 +131,7 @@ public static String tModelsUrl(ApiClient apiClient, @Nullable Object baseModels *

    This is used in the converters. */ @SuppressWarnings("PatternMatchingInstanceof") - public static @Nullable JsonNode tExtractModels(ApiClient apiClient, Object origin) { + public static @Nullable JsonNode tExtractModels(Object origin) { if (origin == null) { return null; } @@ -153,7 +164,7 @@ public static String tModelsUrl(ApiClient apiClient, @Nullable Object baseModels * *

    This is used in the converters. */ - public static Object tContents(ApiClient apiClient, Object origin) { + public static Object tContents(Object origin) { return origin; } @@ -186,12 +197,11 @@ public static ImmutableList tContents(Content content) { /** * Transforms an object to a Content for the API. * - * @param apiClient the API client to use for transformation * @param content the object to transform, can be a string or Content * @return the transformed Content * @throws IllegalArgumentException if the object is not a supported type */ - public static Content tContent(ApiClient apiClient, Object content) { + public static Content tContent(Object content) { if (content == null) { return null; } else if (content instanceof String) { @@ -206,7 +216,7 @@ public static Content tContent(ApiClient apiClient, Object content) { } /** Transforms an object to a Schema for the API. */ - public static Schema tSchema(ApiClient apiClient, Object origin) { + public static Schema tSchema(Object origin) { if (origin == null) { return null; } else if (origin instanceof Schema) { @@ -217,7 +227,7 @@ public static Schema tSchema(ApiClient apiClient, Object origin) { throw new IllegalArgumentException("Unsupported schema type: " + origin.getClass()); } - public static SpeechConfig tSpeechConfig(ApiClient apiClient, Object speechConfig) { + public static SpeechConfig tSpeechConfig(Object speechConfig) { if (speechConfig == null) { return null; } else if (speechConfig instanceof String) { @@ -240,13 +250,12 @@ public static SpeechConfig tSpeechConfig(ApiClient apiClient, Object speechConfi /** * Transforms a SpeechConfig object for the live API, validating it. * - * @param apiClient the API client to use for transformation * @param origin the object to transform, can be a SpeechConfig or a JsonNode * @return the transformed SpeechConfig * @throws IllegalArgumentException if the object is not a supported type or if * multiSpeakerVoiceConfig is present. */ - public static @Nullable SpeechConfig tLiveSpeechConfig(ApiClient apiClient, Object origin) { + public static @Nullable SpeechConfig tLiveSpeechConfig(Object origin) { SpeechConfig speechConfig; if (origin == null) { return null; @@ -272,12 +281,12 @@ public static SpeechConfig tSpeechConfig(ApiClient apiClient, Object speechConfi * *

    This is used in the converters. */ - public static Object tTools(ApiClient apiClient, Object origin) { + public static Object tTools(Object origin) { return origin; } /** Transforms an object to a Tool for the API. */ - public static Tool tTool(ApiClient apiClient, Object origin) { + public static Tool tTool(Object origin) { if (origin == null) { return null; } else if (origin instanceof Tool) { @@ -302,7 +311,6 @@ public static Tool tTool(ApiClient apiClient, Object origin) { // in case reflectMethods is present in the json node, call tTool to parse it and remove it // from the json node. return tTool( - apiClient, JsonSerializable.objectMapper.convertValue( (JsonNode) origin, new TypeReference() {})); } @@ -311,7 +319,7 @@ public static Tool tTool(ApiClient apiClient, Object origin) { } /** Dummy Blobs transformer. */ - public static ArrayNode tBlobs(ApiClient apiClient, Object origin) { + public static ArrayNode tBlobs(Object origin) { // 1. Check if the origin is a JsonNode if (!(origin instanceof JsonNode)) { // If origin is not a JsonNode, we create one from the object. @@ -327,11 +335,11 @@ public static ArrayNode tBlobs(ApiClient apiClient, Object origin) { // 2. If it's not an array, create a new array and add the input to it. ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode(); - arrayNode.add(JsonSerializable.toJsonNode(tBlob(apiClient, origin))); + arrayNode.add(JsonSerializable.toJsonNode(tBlob(origin))); return arrayNode; } - public static Blob tBlob(ApiClient apiClient, Object blob) { + public static Blob tBlob(Object blob) { if (blob instanceof JsonNode) { blob = JsonSerializable.objectMapper.convertValue((JsonNode) blob, new TypeReference() {}); @@ -347,13 +355,12 @@ public static Blob tBlob(ApiClient apiClient, Object blob) { /** * Transforms a blob to an image blob, validating its mime type. * - * @param apiClient the API client to use for transformation * @param blob the object to transform, can be a Blob or a dictionary. * @return the transformed Blob if it is an image. * @throws IllegalArgumentException if the blob is not an image. */ - public static Blob tImageBlob(ApiClient apiClient, Object blob) { - Blob transformedBlob = tBlob(apiClient, blob); + public static Blob tImageBlob(Object blob) { + Blob transformedBlob = tBlob(blob); if (transformedBlob.mimeType().isPresent() && transformedBlob.mimeType().get().startsWith("image/")) { return transformedBlob; @@ -365,13 +372,12 @@ public static Blob tImageBlob(ApiClient apiClient, Object blob) { /** * Transforms a blob to an audio blob, validating its mime type. * - * @param apiClient the API client to use for transformation * @param blob the object to transform, can be a Blob or a dictionary. * @return the transformed Blob if it is an audio. * @throws IllegalArgumentException if the blob is not an audio. */ - public static Blob tAudioBlob(ApiClient apiClient, Object blob) { - Blob transformedBlob = tBlob(apiClient, blob); + public static Blob tAudioBlob(Object blob) { + Blob transformedBlob = tBlob(blob); if (transformedBlob.mimeType().isPresent() && transformedBlob.mimeType().get().startsWith("audio/")) { return transformedBlob; @@ -381,7 +387,7 @@ public static Blob tAudioBlob(ApiClient apiClient, Object blob) { } /** Dummy bytes transformer. */ - public static Object tBytes(ApiClient apiClient, Object origin) { + public static Object tBytes(Object origin) { // TODO(b/389133914): Remove dummy bytes converter. return origin; } @@ -461,7 +467,7 @@ public static String tCachedContentName(ApiClient apiClient, Object origin) { return model; } - public static @Nullable String tFileName(ApiClient apiClient, Object origin) { + public static @Nullable String tFileName(Object origin) { String name = null; if (origin instanceof String) { @@ -507,9 +513,36 @@ public static String tCachedContentName(ApiClient apiClient, Object origin) { return name; } + public static JobState tTuningJobStatus(Object origin) { + String status; + if (origin instanceof String) { + status = (String) origin; + } else if (origin instanceof TextNode) { + status = ((TextNode) origin).textValue(); + } else { + throw new IllegalArgumentException("Unsupported status type: " + origin.getClass()); + } + + switch (status) { + case "STATE_UNSPECIFIED": + return new JobState(JobState.Known.JOB_STATE_UNSPECIFIED); + case "CREATING": + return new JobState(JobState.Known.JOB_STATE_RUNNING); + case "ACTIVE": + return new JobState(JobState.Known.JOB_STATE_SUCCEEDED); + case "FAILED": + return new JobState(JobState.Known.JOB_STATE_FAILED); + default: + return new JobState(status); + } + } + /** Formats a resource name given the resource name and resource prefix. */ private static String getResourceName( ApiClient apiClient, String resourceName, String resourcePrefix) { + boolean shouldPrependCollectionIdentifier = + (!resourceName.startsWith(resourcePrefix + "/") + && countCharInAString(String.format("%s/%s", resourcePrefix, resourceName), '/') == 1); if (apiClient.vertexAI()) { if (resourceName.startsWith("projects/")) { return resourceName; @@ -518,17 +551,233 @@ private static String getResourceName( } else if (resourceName.startsWith(resourcePrefix + "/")) { return String.format( "projects/%s/locations/%s/%s", apiClient.project(), apiClient.location(), resourceName); - } else { + } else if (shouldPrependCollectionIdentifier) { return String.format( "projects/%s/locations/%s/%s/%s", apiClient.project(), apiClient.location(), resourcePrefix, resourceName); + } else { + return resourceName; } } else { - if (resourceName.startsWith(resourcePrefix + "/")) { + if (shouldPrependCollectionIdentifier) { + return String.format("%s/%s", resourcePrefix, resourceName); + } else { return resourceName; + } + } + } + + private static int countCharInAString(String string, char charToCount) { + int count = 0; + for (char c : string.toCharArray()) { + if (c == charToCount) { + count++; + } + } + return count; + } + + public static Object tBatchJobSource(Object src) { + return src; + } + + 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). + * + * @param apiClient The ApiClient instance, used to determine the backend. + * @param name The batch job name as an Object, expected to be a String. + * @return The extracted name (e.g., job ID). + * @throws IllegalArgumentException If the input name is not a String or does not match expected + * patterns. + */ + public static String tBatchJobName(ApiClient apiClient, Object name) { + String nameStr; + if (name instanceof String) { + nameStr = (String) name; + } else if (name instanceof JsonNode) { + nameStr = JsonSerializable.toJsonString((JsonNode) name); + nameStr = nameStr.replace("\"", ""); + } else { + throw new IllegalArgumentException("Unsupported batch job name type: " + name.getClass()); + } + + if (apiClient.vertexAI()) { + String fullBatchName = getResourceName(apiClient, nameStr, "batchPredictionJobs"); + if (fullBatchName != null) { + String[] parts = fullBatchName.split("/"); + String jobId = parts[parts.length - 1]; + Pattern pattern = Pattern.compile("[0-9]+"); + Matcher matcher = pattern.matcher(jobId); + if (matcher.find() && parts.length == 6) { + return jobId; + } + } + throw new IllegalArgumentException( + String.format( + "Invalid batch job name: %s. Expected format like" + + " 'projects/123/locations/us-central1/batchPredictionJobs/456' or '456'.", + nameStr)); + } else { + nameStr = nameStr.replace("\"", ""); + if (nameStr.startsWith("batches/")) { + return nameStr.split("/")[1]; + } + throw new IllegalArgumentException( + String.format("Invalid batch job name: %s. Expected format like 'batches/id'", nameStr)); + } + } + + /** + * Maps specific batch states to job states, otherwise returns the state as is. + * + * @param state The input state as an Object, expected to be a String. + * @return The mapped or original state string. + * @throws IllegalArgumentException If the input state is not a String. + */ + public static Object tJobState(Object state) { + String stateStr; + if (state instanceof String) { + stateStr = (String) state; + } else if (state instanceof JsonNode) { + stateStr = JsonSerializable.toJsonString(state); + stateStr = stateStr.replace("\"", ""); + } else { + throw new IllegalArgumentException("Unsupported job state type: " + state.getClass()); + } + switch (stateStr) { + case "BATCH_STATE_UNSPECIFIED": + 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; + } + } + + /** + * Updates a JSON node with a new value, handling potential conflicts. + * + * @param currentObject The ObjectNode to update. + * @param keyToSet The key to set in the ObjectNode. + * @param valueNode The new JsonNode value. + * @throws IllegalArgumentException if a value cannot be set for an existing key. + */ + public static void updateJsonNode(ObjectNode currentObject, String keyToSet, JsonNode valueNode) { + JsonNode existingData = currentObject.get(keyToSet); + + if (existingData != null) { + // Don't overwrite existing non-empty value with new empty value. + if (valueNode == null || valueNode.isNull() || valueNode.isEmpty()) { + return; + } + + // Don't fail when overwriting value with same value + if (valueNode.equals(existingData)) { + return; + } + + // Instead of overwriting dictionary with another dictionary, merge them. + if (existingData.isObject() && valueNode.isObject()) { + ((ObjectNode) existingData).setAll((ObjectNode) valueNode); } else { - return String.format("%s/%s", resourcePrefix, resourceName); + throw new IllegalArgumentException( + "Cannot set value for an existing key. Key: " + + keyToSet + + "; Existing value: " + + existingData + + "; New value: " + + valueNode); + } + } else { + currentObject.set(keyToSet, valueNode); + } + } + + /** + * Converts a camelCase string to snake_case. + * + * @param str The input string to convert. + * @return The converted string in snake_case. + */ + public static String camelToSnake(String str) { + if (str == null || str.isEmpty()) { + return str; + } + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (Character.isUpperCase(c)) { + if (i > 0) { + sb.append('_'); + } } + sb.append(Character.toLowerCase(c)); + } + + return sb.toString(); + } + + /** + * Prepares the metric payload for the evaluation request. + * + * @param metrics An object containing the metrics to be transformed. + * @return The list of transformed metric payloads. + */ + public static ArrayNode tMetrics(Object metrics) { + if (metrics == null) { + return JsonNodeFactory.instance.arrayNode(); } + + ObjectMapper objectMapper = new ObjectMapper(); + List metricsList = + objectMapper.convertValue(metrics, new TypeReference>() {}); + + List metricsPayload = new ArrayList<>(); + for (UnifiedMetric metricObj : metricsList) { + ObjectNode metricPayloadItem = (ObjectNode) JsonSerializable.toJsonNode(metricObj); + ArrayNode aggregationMetrics = JsonNodeFactory.instance.arrayNode(); + aggregationMetrics.add("AVERAGE"); + aggregationMetrics.add("STANDARD_DEVIATION"); + metricPayloadItem.set("aggregation_metrics", aggregationMetrics); + metricsPayload.add(metricPayloadItem); + } + + ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode(); + for (ObjectNode node : metricsPayload) { + arrayNode.add(node); + } + return arrayNode; + } + + /** + * Checks if a given model name is a Vertex AI embed content model. + * + * @param model The model name to check. + * @return True if the model is a Vertex AI embed content model, false otherwise. + */ + public static boolean tIsVertexEmbedContentModel(String model) { + // Gemini Embeddings except gemini-embedding-001. + return (model.contains("gemini") && !model.contains("gemini-embedding-001")) + // Open-source MaaS embedding models. + || model.contains("maas"); } } diff --git a/src/main/java/com/google/genai/Tunings.java b/src/main/java/com/google/genai/Tunings.java new file mode 100644 index 00000000000..fb79ae7ec49 --- /dev/null +++ b/src/main/java/com/google/genai/Tunings.java @@ -0,0 +1,2288 @@ +/* + * 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.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.CancelTuningJobResponse; +import com.google.genai.types.CreateTuningJobConfig; +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) { + this.apiClient = apiClient; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode cancelTuningJobParametersToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode cancelTuningJobParametersToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode cancelTuningJobResponseFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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 cancelTuningJobResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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 createTuningJobConfigToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"validationDataset"}))) { + throw new IllegalArgumentException( + "validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"displayName"}, + Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"description"}))) { + throw new IllegalArgumentException( + "description parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"epochCount"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"tuningTask", "hyperparameters", "epochCount"}, + Common.getValueByPath(fromObject, new String[] {"epochCount"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"learningRateMultiplier"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"tuningTask", "hyperparameters", "learningRateMultiplier"}, + Common.getValueByPath(fromObject, new String[] {"learningRateMultiplier"})); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"exportLastCheckpointOnly"}))) { + throw new IllegalArgumentException( + "exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"preTunedModelCheckpointId"}))) { + throw new IllegalArgumentException( + "preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent" + + " Platform mode, not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"adapterSize"}))) { + throw new IllegalArgumentException( + "adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"tuningMode"}))) { + throw new IllegalArgumentException( + "tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"customBaseModel"}))) { + throw new IllegalArgumentException( + "customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"batchSize"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"tuningTask", "hyperparameters", "batchSize"}, + Common.getValueByPath(fromObject, new String[] {"batchSize"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"learningRate"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"tuningTask", "hyperparameters", "learningRate"}, + Common.getValueByPath(fromObject, new String[] {"learningRate"})); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"evaluationConfig"}))) { + throw new IllegalArgumentException( + "evaluationConfig parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"labels"}))) { + throw new IllegalArgumentException( + "labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"beta"}))) { + throw new IllegalArgumentException( + "beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"baseTeacherModel"}))) { + throw new IllegalArgumentException( + "baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode," + + " not in Gemini Developer API mode."); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"tunedTeacherModelSource"}))) { + throw new IllegalArgumentException( + "tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"sftLossWeightMultiplier"}))) { + throw new IllegalArgumentException( + "sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"outputUri"}))) { + throw new IllegalArgumentException( + "outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"encryptionSpec"}))) { + throw new IllegalArgumentException( + "encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not" + + " in Gemini Developer API mode."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode createTuningJobConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + 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)); + } + } else if (discriminatorValueValidationDataset.equals("DISTILLATION")) { + if (Common.getValueByPath(fromObject, new String[] {"validationDataset"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec"}, + tuningValidationDatasetToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"validationDataset"})), + toObject, + rootObject)); + } + } + if (Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"tunedModelDisplayName"}, + Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"description"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); + } + + 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"})); + } + } else if (discriminatorValueEpochCount.equals("DISTILLATION")) { + if (Common.getValueByPath(fromObject, new String[] {"epochCount"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "hyperParameters", "epochCount"}, + Common.getValueByPath(fromObject, new String[] {"epochCount"})); + } + } + + 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"})); + } + } else if (discriminatorValueLearningRateMultiplier.equals("DISTILLATION")) { + if (Common.getValueByPath(fromObject, new String[] {"learningRateMultiplier"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "hyperParameters", "learningRateMultiplier"}, + Common.getValueByPath(fromObject, new String[] {"learningRateMultiplier"})); + } + } + + 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"})); + } + } else if (discriminatorValueExportLastCheckpointOnly.equals("DISTILLATION")) { + if (Common.getValueByPath(fromObject, new String[] {"exportLastCheckpointOnly"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "exportLastCheckpointOnly"}, + Common.getValueByPath(fromObject, new String[] {"exportLastCheckpointOnly"})); + } + } + + 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"})); + } + } else if (discriminatorValueAdapterSize.equals("DISTILLATION")) { + if (Common.getValueByPath(fromObject, new String[] {"adapterSize"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "hyperParameters", "adapterSize"}, + Common.getValueByPath(fromObject, new String[] {"adapterSize"})); + } + } + + JsonNode discriminatorTuningMode = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"config", "method"}); + String discriminatorValueTuningMode = + discriminatorTuningMode == null + ? "SUPERVISED_FINE_TUNING" + : discriminatorTuningMode.asText(); + if (discriminatorValueTuningMode.equals("SUPERVISED_FINE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"tuningMode"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"supervisedTuningSpec", "tuningMode"}, + Common.getValueByPath(fromObject, new String[] {"tuningMode"})); + } + } else if (discriminatorValueTuningMode.equals("DISTILLATION")) { + if (Common.getValueByPath(fromObject, new String[] {"tuningMode"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "tuningMode"}, + Common.getValueByPath(fromObject, new String[] {"tuningMode"})); + } + } + if (Common.getValueByPath(fromObject, new String[] {"customBaseModel"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"customBaseModel"}, + Common.getValueByPath(fromObject, new String[] {"customBaseModel"})); + } + + JsonNode discriminatorBatchSize = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"config", "method"}); + String discriminatorValueBatchSize = + discriminatorBatchSize == null ? "SUPERVISED_FINE_TUNING" : discriminatorBatchSize.asText(); + if (discriminatorValueBatchSize.equals("SUPERVISED_FINE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"batchSize"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"supervisedTuningSpec", "hyperParameters", "batchSize"}, + Common.getValueByPath(fromObject, new String[] {"batchSize"})); + } + } else if (discriminatorValueBatchSize.equals("DISTILLATION")) { + if (Common.getValueByPath(fromObject, new String[] {"batchSize"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "hyperParameters", "batchSize"}, + Common.getValueByPath(fromObject, new String[] {"batchSize"})); + } + } + + JsonNode discriminatorLearningRate = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"config", "method"}); + String discriminatorValueLearningRate = + discriminatorLearningRate == null + ? "SUPERVISED_FINE_TUNING" + : discriminatorLearningRate.asText(); + if (discriminatorValueLearningRate.equals("SUPERVISED_FINE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"learningRate"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"supervisedTuningSpec", "hyperParameters", "learningRate"}, + Common.getValueByPath(fromObject, new String[] {"learningRate"})); + } + } else if (discriminatorValueLearningRate.equals("DISTILLATION")) { + if (Common.getValueByPath(fromObject, new String[] {"learningRate"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "hyperParameters", "learningRate"}, + Common.getValueByPath(fromObject, new String[] {"learningRate"})); + } + } + + JsonNode discriminatorEvaluationConfig = + (JsonNode) Common.getValueByPath(rootObject, new String[] {"config", "method"}); + String discriminatorValueEvaluationConfig = + discriminatorEvaluationConfig == null + ? "SUPERVISED_FINE_TUNING" + : discriminatorEvaluationConfig.asText(); + if (discriminatorValueEvaluationConfig.equals("SUPERVISED_FINE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"evaluationConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"supervisedTuningSpec", "evaluationConfig"}, + evaluationConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"evaluationConfig"})), + toObject, + rootObject)); + } + } else if (discriminatorValueEvaluationConfig.equals("PREFERENCE_TUNING")) { + if (Common.getValueByPath(fromObject, new String[] {"evaluationConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"preferenceOptimizationSpec", "evaluationConfig"}, + evaluationConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"evaluationConfig"})), + toObject, + rootObject)); + } + } else if (discriminatorValueEvaluationConfig.equals("DISTILLATION")) { + if (Common.getValueByPath(fromObject, new String[] {"evaluationConfig"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "evaluationConfig"}, + evaluationConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"evaluationConfig"})), + toObject, + rootObject)); + } + } + 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[] {"beta"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"preferenceOptimizationSpec", "hyperParameters", "beta"}, + Common.getValueByPath(fromObject, new String[] {"beta"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"baseTeacherModel"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "baseTeacherModel"}, + Common.getValueByPath(fromObject, new String[] {"baseTeacherModel"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"tunedTeacherModelSource"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "tunedTeacherModelSource"}, + Common.getValueByPath(fromObject, new String[] {"tunedTeacherModelSource"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"sftLossWeightMultiplier"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "hyperParameters", "sftLossWeightMultiplier"}, + Common.getValueByPath(fromObject, new String[] {"sftLossWeightMultiplier"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"outputUri"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"outputUri"}, + Common.getValueByPath(fromObject, new String[] {"outputUri"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"encryptionSpec"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"encryptionSpec"}, + Common.getValueByPath(fromObject, new String[] {"encryptionSpec"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode createTuningJobParametersPrivateToMldev( + 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[] {"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, + rootObject); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode createTuningJobParametersPrivateToVertex( + 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[] {"preTunedModel"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"preTunedModel"}, + Common.getValueByPath(fromObject, new String[] {"preTunedModel"})); + } + + 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 evaluationConfigFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"metrics"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"metrics"}, + Transformers.tMetrics(Common.getValueByPath(fromObject, new String[] {"metrics"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"outputConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"outputConfig"}, + Common.getValueByPath(fromObject, new String[] {"outputConfig"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"autoraterConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"autoraterConfig"}, + Common.getValueByPath(fromObject, new String[] {"autoraterConfig"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"inferenceGenerationConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"inferenceGenerationConfig"}, + generationConfigFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"inferenceGenerationConfig"})), + toObject, + rootObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode evaluationConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"metrics"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"metrics"}, + Transformers.tMetrics(Common.getValueByPath(fromObject, new String[] {"metrics"}))); + } + + if (Common.getValueByPath(fromObject, new String[] {"outputConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"outputConfig"}, + Common.getValueByPath(fromObject, new String[] {"outputConfig"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"autoraterConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"autoraterConfig"}, + Common.getValueByPath(fromObject, new String[] {"autoraterConfig"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"inferenceGenerationConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"inferenceGenerationConfig"}, + generationConfigToVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"inferenceGenerationConfig"})), + toObject, + rootObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generationConfigFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + if (Common.getValueByPath(fromObject, new String[] {"modelConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"modelSelectionConfig"}, + Common.getValueByPath(fromObject, new String[] {"modelConfig"})); + } + + 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[] {"audioTimestamp"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"audioTimestamp"}, + Common.getValueByPath(fromObject, new String[] {"audioTimestamp"})); + } + + 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[] {"enableAffectiveDialog"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"enableAffectiveDialog"}, + Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"})); + } + + 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[] {"logprobs"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"logprobs"}, + Common.getValueByPath(fromObject, new String[] {"logprobs"})); + } + + 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[] {"mediaResolution"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); + } + + 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[] {"responseLogprobs"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); + } + + 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[] {"responseModalities"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseModalities"}, + Common.getValueByPath(fromObject, new String[] {"responseModalities"})); + } + + 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[] {"routingConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"routingConfig"}, + Common.getValueByPath(fromObject, new String[] {"routingConfig"})); + } + + 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[] {"speechConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"speechConfig"}, + Common.getValueByPath(fromObject, new String[] {"speechConfig"})); + } + + 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[] {"temperature"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"temperature"}, + Common.getValueByPath(fromObject, new String[] {"temperature"})); + } + + 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[] {"topK"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode generationConfigToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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[] {"responseJsonSchema"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseJsonSchema"}, + Common.getValueByPath(fromObject, new String[] {"responseJsonSchema"})); + } + + 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[] {"candidateCount"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"candidateCount"}, + Common.getValueByPath(fromObject, new String[] {"candidateCount"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"enableAffectiveDialog"}, + Common.getValueByPath(fromObject, new String[] {"enableAffectiveDialog"})); + } + + 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[] {"logprobs"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"logprobs"}, + Common.getValueByPath(fromObject, new String[] {"logprobs"})); + } + + 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[] {"mediaResolution"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"mediaResolution"}, + Common.getValueByPath(fromObject, new String[] {"mediaResolution"})); + } + + 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[] {"responseLogprobs"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseLogprobs"}, + Common.getValueByPath(fromObject, new String[] {"responseLogprobs"})); + } + + 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[] {"responseModalities"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"responseModalities"}, + Common.getValueByPath(fromObject, new String[] {"responseModalities"})); + } + + 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[] {"routingConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"routingConfig"}, + Common.getValueByPath(fromObject, new String[] {"routingConfig"})); + } + + 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[] {"speechConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"speechConfig"}, + Common.getValueByPath(fromObject, new String[] {"speechConfig"})); + } + + 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[] {"temperature"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"temperature"}, + Common.getValueByPath(fromObject, new String[] {"temperature"})); + } + + 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[] {"topK"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"topK"}, + Common.getValueByPath(fromObject, new String[] {"topK"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"topP"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"topP"}, + Common.getValueByPath(fromObject, new String[] {"topP"})); + } + + if (!Common.isZero( + Common.getValueByPath(fromObject, new String[] {"enableEnhancedCivicAnswers"}))) { + throw new IllegalArgumentException( + "enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not" + + " in Gemini Enterprise Agent Platform mode."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode getTuningJobParametersToMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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"})); + } + + 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( + toObject, + new String[] {"_url", "name"}, + Common.getValueByPath(fromObject, new String[] {"name"})); + } + + return toObject; + } + + @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[] {"_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 listTuningJobsParametersToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + 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 listTuningJobsResponseFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"tuningJobs"}) != null) { + ArrayNode keyArray = + (ArrayNode) Common.getValueByPath(fromObject, new String[] {"tuningJobs"}); + ObjectMapper objectMapper = new ObjectMapper(); + ArrayNode result = objectMapper.createArrayNode(); + + for (JsonNode item : keyArray) { + result.add(tuningJobFromVertex(JsonSerializable.toJsonNode(item), toObject, rootObject)); + } + Common.setValueByPath(toObject, new String[] {"tuningJobs"}, result); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode tunedModelFromMldev( + 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"})); + } + + return toObject; + } + + @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 only supported in Gemini Enterprise Agent Platform mode, not in" + + " Gemini Developer API mode."); + } + + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"}))) { + throw new IllegalArgumentException( + "vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform" + + " mode, not in Gemini Developer API mode."); + } + + if (Common.getValueByPath(fromObject, new String[] {"examples"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"examples", "examples"}, + Common.getValueByPath(fromObject, new String[] {"examples"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode tuningDatasetToVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + ObjectNode toObject = JsonSerializable.objectMapper().createObjectNode(); + + 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"})); + } + } else if (discriminatorValueGcsUri.equals("DISTILLATION")) { + if (Common.getValueByPath(fromObject, new String[] {"gcsUri"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "promptDatasetUri"}, + Common.getValueByPath(fromObject, new String[] {"gcsUri"})); + } + } + + 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"})); + } + } 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"})); + } + } else if (discriminatorValueVertexDatasetResource.equals("DISTILLATION")) { + if (Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"}) != null) { + Common.setValueByPath( + parentObject, + new String[] {"distillationSpec", "promptDatasetUri"}, + Common.getValueByPath(fromObject, new String[] {"vertexDatasetResource"})); + } + } + if (!Common.isZero(Common.getValueByPath(fromObject, new String[] {"examples"}))) { + throw new IllegalArgumentException( + "examples parameter is only supported in Gemini Developer API mode, not in Gemini" + + " Enterprise Agent Platform mode."); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode tuningJobFromMldev(JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"state"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"state"}, + Transformers.tTuningJobStatus(Common.getValueByPath(fromObject, new String[] {"state"}))); + } + + 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[] {"tuningTask", "startTime"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"startTime"}, + Common.getValueByPath(fromObject, new String[] {"tuningTask", "startTime"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"tuningTask", "completeTime"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"endTime"}, + Common.getValueByPath(fromObject, new String[] {"tuningTask", "completeTime"})); + } + + 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[] {"description"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"description"}, + Common.getValueByPath(fromObject, new String[] {"description"})); + } + + 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[] {"_self"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"tunedModel"}, + tunedModelFromMldev( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"_self"})), + toObject, + rootObject)); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode tuningJobFromVertex( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"state"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"state"}, + Transformers.tTuningJobStatus(Common.getValueByPath(fromObject, new String[] {"state"}))); + } + + 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[] {"error"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"error"}, + Common.getValueByPath(fromObject, new String[] {"error"})); + } + + 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[] {"baseModel"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"baseModel"}, + Common.getValueByPath(fromObject, new String[] {"baseModel"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"tunedModel"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"tunedModel"}, + 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) { + Common.setValueByPath( + toObject, + new String[] {"supervisedTuningSpec"}, + 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[] {"distillationSpec"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"distillationSpec"}, + Common.getValueByPath(fromObject, new String[] {"distillationSpec"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"tuningDataStats"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"tuningDataStats"}, + Common.getValueByPath(fromObject, new String[] {"tuningDataStats"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"encryptionSpec"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"encryptionSpec"}, + Common.getValueByPath(fromObject, new String[] {"encryptionSpec"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"partnerModelTuningSpec"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"partnerModelTuningSpec"}, + Common.getValueByPath(fromObject, new String[] {"partnerModelTuningSpec"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"evaluationConfig"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"evaluationConfig"}, + evaluationConfigFromVertex( + JsonSerializable.toJsonNode( + Common.getValueByPath(fromObject, new String[] {"evaluationConfig"})), + toObject, + rootObject)); + } + + if (Common.getValueByPath(fromObject, new String[] {"customBaseModel"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"customBaseModel"}, + Common.getValueByPath(fromObject, new String[] {"customBaseModel"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"evaluateDatasetRuns"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"evaluateDatasetRuns"}, + Common.getValueByPath(fromObject, new String[] {"evaluateDatasetRuns"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"experiment"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"experiment"}, + Common.getValueByPath(fromObject, new String[] {"experiment"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"fullFineTuningSpec"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"fullFineTuningSpec"}, + Common.getValueByPath(fromObject, new String[] {"fullFineTuningSpec"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"labels"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"labels"}, + Common.getValueByPath(fromObject, new String[] {"labels"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"outputUri"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"outputUri"}, + Common.getValueByPath(fromObject, new String[] {"outputUri"})); + } + + 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[] {"serviceAccount"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"serviceAccount"}, + Common.getValueByPath(fromObject, new String[] {"serviceAccount"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"tunedModelDisplayName"}, + Common.getValueByPath(fromObject, new String[] {"tunedModelDisplayName"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"tuningJobState"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"tuningJobState"}, + Common.getValueByPath(fromObject, new String[] {"tuningJobState"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"veoTuningSpec"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"veoTuningSpec"}, + Common.getValueByPath(fromObject, new String[] {"veoTuningSpec"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"distillationSamplingSpec"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"distillationSamplingSpec"}, + Common.getValueByPath(fromObject, new String[] {"distillationSamplingSpec"})); + } + + if (Common.getValueByPath(fromObject, new String[] {"tuningJobMetadata"}) != null) { + Common.setValueByPath( + toObject, + new String[] {"tuningJobMetadata"}, + Common.getValueByPath(fromObject, new String[] {"tuningJobMetadata"})); + } + + return toObject; + } + + @ExcludeFromGeneratedCoverageReport + ObjectNode tuningOperationFromMldev( + JsonNode fromObject, ObjectNode parentObject, JsonNode rootObject) { + 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[] {"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"})); + } + + return toObject; + } + + @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(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = getTuningJobParametersToVertex(parameterNode, null, parameterNode); + path = Common.formatMap("{name}", body.get("_url")); + } else { + body = getTuningJobParametersToMldev(parameterNode, null, parameterNode); + if (body.get("_url") != null) { + path = Common.formatMap("{name}", body.get("_url")); + } else { + path = "{name}"; + } + } + 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. */ + TuningJob processResponseForPrivateGet( + ApiResponse response, GetTuningJobConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + responseNode = tuningJobFromMldev(responseNode, null, parameterNode); + } + + 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) { + GetTuningJobParameters.Builder parameterBuilder = GetTuningJobParameters.builder(); + + if (!Common.isZero(name)) { + parameterBuilder.name(name); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = buildRequestForPrivateGet(name, config); + + try (ApiResponse response = + this.apiClient.request( + "get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateGet(response, config, parameterNode); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateList(ListTuningJobsConfig config) { + + ListTuningJobsParameters.Builder parameterBuilder = ListTuningJobsParameters.builder(); + + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = listTuningJobsParametersToVertex(parameterNode, null, parameterNode); + path = Common.formatMap("tuningJobs", body.get("_url")); + } else { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } + 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. */ + ListTuningJobsResponse processResponseForPrivateList( + ApiResponse response, ListTuningJobsConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } + + 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) { + ListTuningJobsParameters.Builder parameterBuilder = ListTuningJobsParameters.builder(); + + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = buildRequestForPrivateList(config); + + try (ApiResponse response = + this.apiClient.request( + "get", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateList(response, config, parameterNode); + } + } + + /** 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()); + + 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 { + path = "{name}:cancel"; + } + } + 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. */ + CancelTuningJobResponse processResponseForCancel( + ApiResponse response, CancelTuningJobConfig config, JsonNode parameterNode) { + 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 = cancelTuningJobResponseFromVertex(responseNode, null, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + responseNode = cancelTuningJobResponseFromMldev(responseNode, null, parameterNode); + } + + CancelTuningJobResponse sdkResponse = + JsonSerializable.fromJsonNode(responseNode, CancelTuningJobResponse.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(); + } + + /** + * Cancels a tuning job resource. + * + * @param name The resource name of the tuning job. For Gemini Enterprise Agent Platform , this is + * the full resource name. For Gemini API, this is `tunedModels/{id}`. + * @param config A {@link CancelTuningJobConfig} for configuring the cancel request. + */ + public CancelTuningJobResponse cancel(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()); + BuiltRequest builtRequest = buildRequestForCancel(name, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForCancel(response, config, parameterNode); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateTune( + String baseModel, + PreTunedModel preTunedModel, + TuningDataset trainingDataset, + CreateTuningJobConfig config) { + + 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); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + body = createTuningJobParametersPrivateToVertex(parameterNode, null, parameterNode); + path = Common.formatMap("tuningJobs", body.get("_url")); + } else { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } + 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. */ + TuningJob processResponseForPrivateTune( + ApiResponse response, CreateTuningJobConfig config, JsonNode parameterNode) { + 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, parameterNode); + } + + if (!this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Enterprise Agent Platform mode, not in Gemini" + + " Developer API mode."); + } + + 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) { + 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); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = + buildRequestForPrivateTune(baseModel, preTunedModel, trainingDataset, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateTune(response, config, parameterNode); + } + } + + /** A shared buildRequest method for both sync and async methods. */ + BuiltRequest buildRequestForPrivateTuneMldev( + String baseModel, + PreTunedModel preTunedModel, + TuningDataset trainingDataset, + CreateTuningJobConfig config) { + + 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); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + + ObjectNode body; + String path; + if (this.apiClient.vertexAI()) { + throw new UnsupportedOperationException( + "This method is only supported in Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } else { + body = createTuningJobParametersPrivateToMldev(parameterNode, null, parameterNode); + if (body.get("_url") != null) { + path = Common.formatMap("tunedModels", body.get("_url")); + } else { + path = "tunedModels"; + } + } + 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. */ + TuningOperation processResponseForPrivateTuneMldev( + ApiResponse response, CreateTuningJobConfig config, JsonNode parameterNode) { + 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 Gemini Developer API mode, not in Gemini Enterprise" + + " Agent Platform mode."); + } + + if (!this.apiClient.vertexAI()) { + responseNode = tuningOperationFromMldev(responseNode, null, parameterNode); + } + + 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) { + 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); + } + if (!Common.isZero(config)) { + parameterBuilder.config(config); + } + JsonNode parameterNode = JsonSerializable.toJsonNode(parameterBuilder.build()); + BuiltRequest builtRequest = + buildRequestForPrivateTuneMldev(baseModel, preTunedModel, trainingDataset, config); + + try (ApiResponse response = + this.apiClient.request( + "post", builtRequest.path(), builtRequest.body(), builtRequest.httpOptions())) { + return processResponseForPrivateTuneMldev(response, config, parameterNode); + } + } + + /** + * Makes an API request to list the available tuning jobs. + * + * @param config A {@link ListTuningJobsConfig} for configuring the list request. + * @return A {@link Pager} object that contains the list of tuning jobs. The pager is an iterable + * and automatically queries the next page once the current page is exhausted. + */ + @SuppressWarnings("PatternMatchingInstanceof") + public Pager list(ListTuningJobsConfig config) { + if (config == null) { + config = ListTuningJobsConfig.builder().build(); + } + Function request = + requestConfig -> { + if (!(requestConfig instanceof ListTuningJobsConfig)) { + throw new GenAiIOException( + "Internal error: Pager expected ListTuningJobsConfig but received " + + requestConfig.getClass().getName()); + } + return this.privateList((ListTuningJobsConfig) requestConfig); + }; + return new Pager<>( + Pager.PagedItem.TUNING_JOBS, + request, + (ObjectNode) JsonSerializable.toJsonNode(config), + JsonSerializable.toJsonNode(privateList(config))); + } + + /** + * Makes an API request to get a tuning job. + * + * @param name The resource name of the tuning job. + * @param config A {@link GetTuningJobConfig} for configuring the get request. + * @return A {@link TuningJob} object. + */ + public TuningJob get(String name, GetTuningJobConfig config) { + return this.privateGet(name, config); + } + + /** + * Makes an API request to create a supervised fine-tuning job. + * + *

    This method is experimental. + * + * @param baseModel The base model to tune. + * @param trainingDataset The training dataset to use for tuning. + * @param config A {@link CreateTuningJobConfig} for configuring the create request. + * @return A {@link TuningJob} object. + */ + public TuningJob tune( + String baseModel, TuningDataset trainingDataset, CreateTuningJobConfig config) { + if (this.apiClient.vertexAI()) { + TuningJob tuningJob; + if (baseModel.startsWith("projects/")) { + PreTunedModel.Builder preTunedModelBuilder = + PreTunedModel.builder().tunedModelName(baseModel); + if (config != null && config.preTunedModelCheckpointId().isPresent()) { + preTunedModelBuilder.checkpointId(config.preTunedModelCheckpointId().get()); + } + tuningJob = this.privateTune(null, preTunedModelBuilder.build(), trainingDataset, config); + } else { + tuningJob = this.privateTune(baseModel, null, trainingDataset, config); + } + if (config != null && config.evaluationConfig().isPresent()) { + tuningJob = tuningJob.toBuilder().evaluationConfig(config.evaluationConfig().get()).build(); + } + return tuningJob; + } else { + TuningOperation operation = this.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 TuningJob.builder() + .name(tunedModelName) + .state(JobState.Known.JOB_STATE_QUEUED) + .build(); + } + } +} diff --git a/src/main/java/com/google/genai/UploadClient.java b/src/main/java/com/google/genai/UploadClient.java index 0319c291d8b..fd3a3b3ecdf 100644 --- a/src/main/java/com/google/genai/UploadClient.java +++ b/src/main/java/com/google/genai/UploadClient.java @@ -17,7 +17,6 @@ package com.google.genai; import com.google.genai.errors.GenAiIOException; -import com.google.common.collect.ImmutableMap; import com.google.genai.types.HttpOptions; import java.io.ByteArrayInputStream; import java.io.File; @@ -26,9 +25,11 @@ import java.io.InputStream; import java.time.Duration; import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; -import org.apache.http.Header; -import org.apache.http.HttpEntity; +import okhttp3.Headers; +import okhttp3.ResponseBody; /** Client which handles the upload process for files on the SDK. */ final class UploadClient { @@ -50,28 +51,61 @@ public UploadClient(ApiClient apiClient, int chunkSize) { this.chunkSize = chunkSize; } - public HttpEntity upload(String uploadUrl, String filePath) { + public static HttpOptions buildResumableUploadHttpOptions( + Optional userOptions, + Optional mimeType, + Optional fileName, + long size) { + String actualMimeType = + mimeType.orElseThrow( + () -> + new IllegalArgumentException( + "Unknown mime type: Could not determine mime type for your file, please" + + " set the mimeType config argument")); + HttpOptions.Builder httpOptionsBuilder = HttpOptions.builder(); + if (userOptions.isPresent()) { + httpOptionsBuilder = userOptions.get().toBuilder(); + } + + Map headers = new HashMap<>(); + headers.put("Content-Type", "application/json"); + headers.put("X-Goog-Upload-Protocol", "resumable"); + headers.put("X-Goog-Upload-Command", "start"); + headers.put("X-Goog-Upload-Header-Content-Length", "" + size); + headers.put("X-Goog-Upload-Header-Content-Type", actualMimeType); + if (fileName.isPresent()) { + headers.put("X-Goog-Upload-File-Name", fileName.get()); + } + + return httpOptionsBuilder.apiVersion("").headers(headers).build(); + } + + public ResponseBody upload(String uploadUrl, String filePath, Optional httpOptions) { File file = new File(filePath); - HttpEntity entity; + ResponseBody responseBody; try (InputStream inputStream = new FileInputStream(file)) { - entity = upload(uploadUrl, inputStream, file.length()); + responseBody = upload(uploadUrl, inputStream, file.length(), httpOptions); } catch (IOException e) { throw new GenAiIOException("Failed to process input stream", e); } - return entity; + return responseBody; } - public HttpEntity upload(String uploadUrl, byte[] bytes) { - HttpEntity entity; + public ResponseBody upload(String uploadUrl, byte[] bytes, Optional httpOptions) { + ResponseBody responseBody; try (InputStream inputStream = new ByteArrayInputStream(bytes)) { - entity = upload(uploadUrl, inputStream, bytes.length); + responseBody = upload(uploadUrl, inputStream, bytes.length, httpOptions); } catch (IOException e) { throw new GenAiIOException("Failed to process input stream", e); } - return entity; + return responseBody; } - public HttpEntity upload(String uploadUrl, InputStream inputStream, long size) { + public ResponseBody upload( + String uploadUrl, + InputStream inputStream, + long size, + Optional httpOptions) { String uploadCommand = "upload"; byte[] buffer = new byte[chunkSize]; int bytesRead; @@ -79,7 +113,7 @@ public HttpEntity upload(String uploadUrl, InputStream inputStream, long size) { try { while ((bytesRead = inputStream.read(buffer, 0, chunkSize)) == chunkSize) { UploadChunkResponse uploadChunkResponse = - uploadChunk(uploadUrl, buffer, offset, uploadCommand); + uploadChunk(uploadUrl, buffer, offset, uploadCommand, httpOptions); String uploadStatus = uploadChunkResponse.getUploadStatus(); offset += bytesRead; if (uploadStatus == null || !uploadStatus.equals("active")) { @@ -92,7 +126,8 @@ public HttpEntity upload(String uploadUrl, InputStream inputStream, long size) { } buffer = Arrays.copyOfRange(buffer, 0, bytesRead); uploadCommand = uploadCommand + ", finalize"; - UploadChunkResponse uploadChunkResponse = uploadChunk(uploadUrl, buffer, offset, uploadCommand); + UploadChunkResponse uploadChunkResponse = + uploadChunk(uploadUrl, buffer, offset, uploadCommand, httpOptions); String uploadStatus = uploadChunkResponse.getUploadStatus(); if (uploadStatus == null || !uploadStatus.equals("final")) { throw new IllegalStateException( @@ -102,28 +137,34 @@ public HttpEntity upload(String uploadUrl, InputStream inputStream, long size) { } private UploadChunkResponse uploadChunk( - String uploadUrl, byte[] chunk, long offset, String uploadCommand) { - HttpOptions httpOptions = - HttpOptions.builder() - .headers( - ImmutableMap.of( - "X-Goog-Upload-Command", - uploadCommand, - "X-Goog-Upload-Offset", - Long.toString(offset))) - .build(); + String uploadUrl, + byte[] chunk, + long offset, + String uploadCommand, + Optional httpOptions) { + HttpOptions.Builder optionsBuilder = + httpOptions.isPresent() ? httpOptions.get().toBuilder() : HttpOptions.builder(); + + Map headers = new HashMap<>(); + if (httpOptions.isPresent() && httpOptions.get().headers().isPresent()) { + headers.putAll(httpOptions.get().headers().get()); + } + headers.put("X-Goog-Upload-Command", uploadCommand); + headers.put("X-Goog-Upload-Offset", Long.toString(offset)); + HttpOptions finalHttpOptions = optionsBuilder.headers(headers).build(); int retryCount = 0; boolean uploadStatusHeaderFound = false; String uploadStatus = ""; ApiResponse response = null; while (retryCount < MAX_RETRY_COUNT) { - response = apiClient.request("POST", uploadUrl, chunk, Optional.of(httpOptions)); - Header[] headers = response.getHeaders(); - for (Header header : headers) { - if (header.getName().equals("X-Goog-Upload-Status")) { + response = apiClient.request("POST", uploadUrl, chunk, Optional.of(finalHttpOptions)); + Headers responseHeaders = response.getHeaders(); + if (responseHeaders != null) { + String headerValue = responseHeaders.get("X-Goog-Upload-Status"); + if (headerValue != null) { uploadStatusHeaderFound = true; - uploadStatus = header.getValue(); + uploadStatus = headerValue; break; } } @@ -144,14 +185,14 @@ private UploadChunkResponse uploadChunk( if (!uploadStatusHeaderFound) { throw new IllegalStateException("Upload failed. Retries exhausted, please try again."); } - return new UploadChunkResponse(uploadStatus, response.getEntity()); + return new UploadChunkResponse(uploadStatus, response.getBody()); } private static class UploadChunkResponse { private final String uploadStatus; - private final HttpEntity entity; + private final ResponseBody entity; - UploadChunkResponse(String uploadStatus, HttpEntity entity) { + UploadChunkResponse(String uploadStatus, ResponseBody entity) { this.uploadStatus = uploadStatus; this.entity = entity; } @@ -160,7 +201,7 @@ public String getUploadStatus() { return uploadStatus; } - public HttpEntity getEntity() { + public ResponseBody getEntity() { return entity; } } diff --git a/src/main/java/com/google/genai/errors/ApiException.java b/src/main/java/com/google/genai/errors/ApiException.java index 042c9d2e6a0..9252aa8e8fe 100644 --- a/src/main/java/com/google/genai/errors/ApiException.java +++ b/src/main/java/com/google/genai/errors/ApiException.java @@ -16,9 +16,15 @@ package com.google.genai.errors; +import static com.google.common.base.Strings.isNullOrEmpty; + import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.google.api.core.InternalApi; import java.io.IOException; +import okhttp3.Response; +import okhttp3.ResponseBody; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; @@ -50,7 +56,10 @@ public ApiException(int code, String status, String message) { * Throws an ApiException from the response if the response is not a OK status. * * @param response The response from the API call. + * @deprecated Use {@link #throwFromResponse(Response)} instead. */ + @ExcludeFromGeneratedCoverageReport + @Deprecated public static void throwFromResponse(CloseableHttpResponse response) { StatusLine statusLine = response.getStatusLine(); int code = statusLine.getStatusCode(); @@ -68,10 +77,34 @@ public static void throwFromResponse(CloseableHttpResponse response) { } } + /** + * Throws an ApiException from the response if the response is not a OK status. + * + * @param response The response from the API call. + */ + @InternalApi + public static void throwFromResponse(Response response) { + int code = response.code(); + if (code >= 200 && code < 300) { + return; + } + String status = response.message(); + String message = getErrorMessageFromResponse(response); + if (code >= 400 && code < 500) { // Client errors. + throw new ClientException(code, status, message); + } else if (code >= 500 && code < 600) { // Server errors. + throw new ServerException(code, status, message); + } else { + throw new ApiException(code, status, message); + } + } + /** * Returns the error message from the response, if no error or error message is not found, then * returns an empty string. */ + @ExcludeFromGeneratedCoverageReport + @Deprecated static String getErrorMessageFromResponse(CloseableHttpResponse response) { HttpEntity entity = response.getEntity(); try { @@ -93,6 +126,92 @@ static String getErrorMessageFromResponse(CloseableHttpResponse response) { } } + /** + * Returns the error message from the response, if no error or error message is not found, then + * returns an empty string. + */ + static String getErrorMessageFromResponse(Response response) { + ResponseBody responseBody = response.body(); + try { + if (responseBody == null) { + return ""; + } + String responseBodyString = responseBody.string(); + if (isNullOrEmpty(responseBodyString)) { + return ""; + } + ObjectMapper mapper = new ObjectMapper(); + JsonNode errorNode = mapper.readTree(responseBodyString).get("error"); + if (errorNode != null && errorNode.isObject()) { + JsonNode messageNode = errorNode.get("message"); + String message = messageNode != null && messageNode.isTextual() ? messageNode.asText() : ""; + + JsonNode detailsNode = errorNode.get("details"); + if (detailsNode != null && detailsNode.isArray()) { + StringBuilder sb = new StringBuilder(); + for (JsonNode item : detailsNode) { + if (item.isObject()) { + JsonNode detailNode = item.get("detail"); + if (detailNode != null && detailNode.isTextual()) { + sb.append(detailNode.asText()).append("\n"); + continue; + } + } + if (!item.isNull()) { + sb.append(item.toString()).append("\n"); + } + } + String detailsText = sb.toString().trim(); + if (!detailsText.isEmpty()) { + return message.isEmpty() + ? "Details: " + detailsText + : message + "\nDetails: " + detailsText; + } + } + return message; + } + return ""; + } catch (IOException ignored) { + return ""; + } + } + + /** Throws an ApiException from a {@link ArrayNode}. This method is for internal use only. */ + @InternalApi + public static void throwFromErrorNode(ArrayNode errorNode, int code) { + if (code == 200) { + return; + } + + String message = ""; + try { + JsonNode messageNode = errorNode.get(0).get("error").get("message"); + if (messageNode != null && messageNode.isTextual()) { + message = messageNode.asText(); + } + } catch (NullPointerException | IndexOutOfBoundsException ignored) { + // If message is not found, do nothing and fallback to default message "". + } + + String status = "UNKNOWN"; + try { + JsonNode statusNode = errorNode.get(0).get("error").get("status"); + if (statusNode != null && statusNode.isTextual()) { + status = statusNode.asText(); + } + } catch (NullPointerException | IndexOutOfBoundsException ignored) { + // If status is not found, do nothing and fallback to default value "UNKNOWN". + } + + if (code >= 400 && code < 500) { // Client errors. + throw new ClientException(code, status, message); + } else if (code >= 500 && code < 600) { // Server errors. + throw new ServerException(code, status, message); + } else { + throw new ApiException(code, status, message); + } + } + /** Returns the status code from the API response. */ public int code() { return code; diff --git a/src/main/java/com/google/genai/errors/BaseException.java b/src/main/java/com/google/genai/errors/BaseException.java index d027d17dff4..efa1feca982 100644 --- a/src/main/java/com/google/genai/errors/BaseException.java +++ b/src/main/java/com/google/genai/errors/BaseException.java @@ -19,9 +19,9 @@ /** * Base exception class for all exceptions specifically originating from the GenAI SDK. * - *

    This class extends {@link RuntimeException}. The GenAI SDK favors unchecked exceptions - * to improve developer experience by reducing mandatory {@code try-catch} or {@code throws} - * clause boilerplate for potentially unrecoverable runtime errors. + *

    This class extends {@link RuntimeException}. The GenAI SDK favors unchecked exceptions to + * improve developer experience by reducing mandatory {@code try-catch} or {@code throws} clause + * boilerplate for potentially unrecoverable runtime errors. */ class BaseException extends RuntimeException { diff --git a/src/main/java/com/google/genai/errors/ExcludeFromGeneratedCoverageReport.java b/src/main/java/com/google/genai/errors/ExcludeFromGeneratedCoverageReport.java new file mode 100644 index 00000000000..50361fab85d --- /dev/null +++ b/src/main/java/com/google/genai/errors/ExcludeFromGeneratedCoverageReport.java @@ -0,0 +1,32 @@ +/* + * 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.errors; + +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/errors/GenAiIOException.java b/src/main/java/com/google/genai/errors/GenAiIOException.java index d456f200de8..c36e4db209c 100644 --- a/src/main/java/com/google/genai/errors/GenAiIOException.java +++ b/src/main/java/com/google/genai/errors/GenAiIOException.java @@ -26,6 +26,11 @@ public GenAiIOException(String message, IOException cause) { super(message, cause); } + /** Creates a new GenAiIoException with the specified message and the original cause. */ + public GenAiIOException(String message, Throwable cause) { + super(message, cause); + } + /** Creates a new GenAiIoException with the specified message. */ public GenAiIOException(String message) { super(message); 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 new file mode 100644 index 00000000000..6a7c765000a --- /dev/null +++ b/src/main/java/com/google/genai/types/AdapterSize.java @@ -0,0 +1,123 @@ +/* + * 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; + +/** Adapter size for tuning. This enum is not supported in Gemini API. */ +public class AdapterSize { + + /** Enum representing the known values for AdapterSize. */ + public enum Known { + /** Adapter size is unspecified. */ + ADAPTER_SIZE_UNSPECIFIED, + + /** Adapter size 1. */ + ADAPTER_SIZE_ONE, + + /** Adapter size 2. */ + ADAPTER_SIZE_TWO, + + /** Adapter size 4. */ + ADAPTER_SIZE_FOUR, + + /** Adapter size 8. */ + ADAPTER_SIZE_EIGHT, + + /** Adapter size 16. */ + ADAPTER_SIZE_SIXTEEN, + + /** Adapter size 32. */ + ADAPTER_SIZE_THIRTY_TWO + } + + private Known adapterSizeEnum; + private final String value; + + @JsonCreator + public AdapterSize(String value) { + this.value = value; + for (Known adapterSizeEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(adapterSizeEnum.toString(), value)) { + this.adapterSizeEnum = adapterSizeEnum; + break; + } + } + if (this.adapterSizeEnum == null) { + this.adapterSizeEnum = Known.ADAPTER_SIZE_UNSPECIFIED; + } + } + + public AdapterSize(Known knownValue) { + this.adapterSizeEnum = 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 AdapterSize)) { + return false; + } + + AdapterSize other = (AdapterSize) o; + + if (this.adapterSizeEnum != Known.ADAPTER_SIZE_UNSPECIFIED + && other.adapterSizeEnum != Known.ADAPTER_SIZE_UNSPECIFIED) { + return this.adapterSizeEnum == other.adapterSizeEnum; + } else if (this.adapterSizeEnum == Known.ADAPTER_SIZE_UNSPECIFIED + && other.adapterSizeEnum == Known.ADAPTER_SIZE_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.adapterSizeEnum != Known.ADAPTER_SIZE_UNSPECIFIED) { + return this.adapterSizeEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.adapterSizeEnum; + } +} diff --git a/src/main/java/com/google/genai/types/AggregationMetric.java b/src/main/java/com/google/genai/types/AggregationMetric.java new file mode 100644 index 00000000000..f9e156e4aab --- /dev/null +++ b/src/main/java/com/google/genai/types/AggregationMetric.java @@ -0,0 +1,135 @@ +/* + * 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; + +/** Aggregation metric. This enum is not supported in Gemini API. */ +public class AggregationMetric { + + /** Enum representing the known values for AggregationMetric. */ + public enum Known { + /** Unspecified aggregation metric. */ + AGGREGATION_METRIC_UNSPECIFIED, + + /** Average aggregation metric. Not supported for Pairwise metric. */ + AVERAGE, + + /** Mode aggregation metric. */ + MODE, + + /** Standard deviation aggregation metric. Not supported for pairwise metric. */ + STANDARD_DEVIATION, + + /** Variance aggregation metric. Not supported for pairwise metric. */ + VARIANCE, + + /** Minimum aggregation metric. Not supported for pairwise metric. */ + MINIMUM, + + /** Maximum aggregation metric. Not supported for pairwise metric. */ + MAXIMUM, + + /** Median aggregation metric. Not supported for pairwise metric. */ + MEDIAN, + + /** 90th percentile aggregation metric. Not supported for pairwise metric. */ + PERCENTILE_P90, + + /** 95th percentile aggregation metric. Not supported for pairwise metric. */ + PERCENTILE_P95, + + /** 99th percentile aggregation metric. Not supported for pairwise metric. */ + PERCENTILE_P99 + } + + private Known aggregationMetricEnum; + private final String value; + + @JsonCreator + public AggregationMetric(String value) { + this.value = value; + for (Known aggregationMetricEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(aggregationMetricEnum.toString(), value)) { + this.aggregationMetricEnum = aggregationMetricEnum; + break; + } + } + if (this.aggregationMetricEnum == null) { + this.aggregationMetricEnum = Known.AGGREGATION_METRIC_UNSPECIFIED; + } + } + + public AggregationMetric(Known knownValue) { + this.aggregationMetricEnum = 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 AggregationMetric)) { + return false; + } + + AggregationMetric other = (AggregationMetric) o; + + if (this.aggregationMetricEnum != Known.AGGREGATION_METRIC_UNSPECIFIED + && other.aggregationMetricEnum != Known.AGGREGATION_METRIC_UNSPECIFIED) { + return this.aggregationMetricEnum == other.aggregationMetricEnum; + } else if (this.aggregationMetricEnum == Known.AGGREGATION_METRIC_UNSPECIFIED + && other.aggregationMetricEnum == Known.AGGREGATION_METRIC_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.aggregationMetricEnum != Known.AGGREGATION_METRIC_UNSPECIFIED) { + return this.aggregationMetricEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.aggregationMetricEnum; + } +} diff --git a/src/main/java/com/google/genai/types/AggregationOutput.java b/src/main/java/com/google/genai/types/AggregationOutput.java new file mode 100644 index 00000000000..2d042663fbc --- /dev/null +++ b/src/main/java/com/google/genai/types/AggregationOutput.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 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; + +/** + * The aggregation result for the entire dataset and all metrics. This data type is not supported in + * Gemini API. + */ +@AutoValue +@JsonDeserialize(builder = AggregationOutput.Builder.class) +public abstract class AggregationOutput extends JsonSerializable { + /** One AggregationResult per metric. */ + @JsonProperty("aggregationResults") + public abstract Optional> aggregationResults(); + + /** The dataset used for evaluation & aggregation. */ + @JsonProperty("dataset") + public abstract Optional dataset(); + + /** Instantiates a builder for AggregationOutput. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_AggregationOutput.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for AggregationOutput. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `AggregationOutput.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_AggregationOutput.Builder(); + } + + /** + * Setter for aggregationResults. + * + *

    aggregationResults: One AggregationResult per metric. + */ + @JsonProperty("aggregationResults") + public abstract Builder aggregationResults(List aggregationResults); + + /** + * Setter for aggregationResults. + * + *

    aggregationResults: One AggregationResult per metric. + */ + @CanIgnoreReturnValue + public Builder aggregationResults(AggregationResult... aggregationResults) { + return aggregationResults(Arrays.asList(aggregationResults)); + } + + /** + * Setter for aggregationResults builder. + * + *

    aggregationResults: One AggregationResult per metric. + */ + @CanIgnoreReturnValue + public Builder aggregationResults(AggregationResult.Builder... aggregationResultsBuilders) { + return aggregationResults( + Arrays.asList(aggregationResultsBuilders).stream() + .map(AggregationResult.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder aggregationResults(Optional> aggregationResults); + + /** Clears the value of aggregationResults field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAggregationResults() { + return aggregationResults(Optional.empty()); + } + + /** + * Setter for dataset. + * + *

    dataset: The dataset used for evaluation & aggregation. + */ + @JsonProperty("dataset") + public abstract Builder dataset(EvaluationDataset dataset); + + /** + * Setter for dataset builder. + * + *

    dataset: The dataset used for evaluation & aggregation. + */ + @CanIgnoreReturnValue + public Builder dataset(EvaluationDataset.Builder datasetBuilder) { + return dataset(datasetBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder dataset(Optional dataset); + + /** Clears the value of dataset field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDataset() { + return dataset(Optional.empty()); + } + + public abstract AggregationOutput build(); + } + + /** Deserializes a JSON string to a AggregationOutput object. */ + @ExcludeFromGeneratedCoverageReport + public static AggregationOutput fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, AggregationOutput.class); + } +} diff --git a/src/main/java/com/google/genai/types/AggregationResult.java b/src/main/java/com/google/genai/types/AggregationResult.java new file mode 100644 index 00000000000..92b6b0f4f40 --- /dev/null +++ b/src/main/java/com/google/genai/types/AggregationResult.java @@ -0,0 +1,298 @@ +/* + * 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; + +/** The aggregation result for a single metric. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = AggregationResult.Builder.class) +public abstract class AggregationResult extends JsonSerializable { + /** Aggregation metric. */ + @JsonProperty("aggregationMetric") + public abstract Optional aggregationMetric(); + + /** Results for bleu metric. */ + @JsonProperty("bleuMetricValue") + public abstract Optional bleuMetricValue(); + + /** Result for code execution metric. */ + @JsonProperty("customCodeExecutionResult") + public abstract Optional customCodeExecutionResult(); + + /** Results for exact match metric. */ + @JsonProperty("exactMatchMetricValue") + public abstract Optional exactMatchMetricValue(); + + /** Result for pairwise metric. */ + @JsonProperty("pairwiseMetricResult") + public abstract Optional pairwiseMetricResult(); + + /** Result for pointwise metric. */ + @JsonProperty("pointwiseMetricResult") + public abstract Optional pointwiseMetricResult(); + + /** Results for rouge metric. */ + @JsonProperty("rougeMetricValue") + public abstract Optional rougeMetricValue(); + + /** Instantiates a builder for AggregationResult. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_AggregationResult.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for AggregationResult. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `AggregationResult.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_AggregationResult.Builder(); + } + + /** + * Setter for aggregationMetric. + * + *

    aggregationMetric: Aggregation metric. + */ + @JsonProperty("aggregationMetric") + public abstract Builder aggregationMetric(AggregationMetric aggregationMetric); + + @ExcludeFromGeneratedCoverageReport + abstract Builder aggregationMetric(Optional aggregationMetric); + + /** Clears the value of aggregationMetric field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAggregationMetric() { + return aggregationMetric(Optional.empty()); + } + + /** + * Setter for aggregationMetric given a known enum. + * + *

    aggregationMetric: Aggregation metric. + */ + @CanIgnoreReturnValue + public Builder aggregationMetric(AggregationMetric.Known knownType) { + return aggregationMetric(new AggregationMetric(knownType)); + } + + /** + * Setter for aggregationMetric given a string. + * + *

    aggregationMetric: Aggregation metric. + */ + @CanIgnoreReturnValue + public Builder aggregationMetric(String aggregationMetric) { + return aggregationMetric(new AggregationMetric(aggregationMetric)); + } + + /** + * Setter for bleuMetricValue. + * + *

    bleuMetricValue: Results for bleu metric. + */ + @JsonProperty("bleuMetricValue") + public abstract Builder bleuMetricValue(BleuMetricValue bleuMetricValue); + + /** + * Setter for bleuMetricValue builder. + * + *

    bleuMetricValue: Results for bleu metric. + */ + @CanIgnoreReturnValue + public Builder bleuMetricValue(BleuMetricValue.Builder bleuMetricValueBuilder) { + return bleuMetricValue(bleuMetricValueBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder bleuMetricValue(Optional bleuMetricValue); + + /** Clears the value of bleuMetricValue field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBleuMetricValue() { + return bleuMetricValue(Optional.empty()); + } + + /** + * Setter for customCodeExecutionResult. + * + *

    customCodeExecutionResult: Result for code execution metric. + */ + @JsonProperty("customCodeExecutionResult") + public abstract Builder customCodeExecutionResult( + CustomCodeExecutionResult customCodeExecutionResult); + + /** + * Setter for customCodeExecutionResult builder. + * + *

    customCodeExecutionResult: Result for code execution metric. + */ + @CanIgnoreReturnValue + public Builder customCodeExecutionResult( + CustomCodeExecutionResult.Builder customCodeExecutionResultBuilder) { + return customCodeExecutionResult(customCodeExecutionResultBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder customCodeExecutionResult( + Optional customCodeExecutionResult); + + /** Clears the value of customCodeExecutionResult field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCustomCodeExecutionResult() { + return customCodeExecutionResult(Optional.empty()); + } + + /** + * Setter for exactMatchMetricValue. + * + *

    exactMatchMetricValue: Results for exact match metric. + */ + @JsonProperty("exactMatchMetricValue") + public abstract Builder exactMatchMetricValue(ExactMatchMetricValue exactMatchMetricValue); + + /** + * Setter for exactMatchMetricValue builder. + * + *

    exactMatchMetricValue: Results for exact match metric. + */ + @CanIgnoreReturnValue + public Builder exactMatchMetricValue( + ExactMatchMetricValue.Builder exactMatchMetricValueBuilder) { + return exactMatchMetricValue(exactMatchMetricValueBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder exactMatchMetricValue(Optional exactMatchMetricValue); + + /** Clears the value of exactMatchMetricValue field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearExactMatchMetricValue() { + return exactMatchMetricValue(Optional.empty()); + } + + /** + * Setter for pairwiseMetricResult. + * + *

    pairwiseMetricResult: Result for pairwise metric. + */ + @JsonProperty("pairwiseMetricResult") + public abstract Builder pairwiseMetricResult(PairwiseMetricResult pairwiseMetricResult); + + /** + * Setter for pairwiseMetricResult builder. + * + *

    pairwiseMetricResult: Result for pairwise metric. + */ + @CanIgnoreReturnValue + public Builder pairwiseMetricResult(PairwiseMetricResult.Builder pairwiseMetricResultBuilder) { + return pairwiseMetricResult(pairwiseMetricResultBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder pairwiseMetricResult(Optional pairwiseMetricResult); + + /** Clears the value of pairwiseMetricResult field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPairwiseMetricResult() { + return pairwiseMetricResult(Optional.empty()); + } + + /** + * Setter for pointwiseMetricResult. + * + *

    pointwiseMetricResult: Result for pointwise metric. + */ + @JsonProperty("pointwiseMetricResult") + public abstract Builder pointwiseMetricResult(PointwiseMetricResult pointwiseMetricResult); + + /** + * Setter for pointwiseMetricResult builder. + * + *

    pointwiseMetricResult: Result for pointwise metric. + */ + @CanIgnoreReturnValue + public Builder pointwiseMetricResult( + PointwiseMetricResult.Builder pointwiseMetricResultBuilder) { + return pointwiseMetricResult(pointwiseMetricResultBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder pointwiseMetricResult(Optional pointwiseMetricResult); + + /** Clears the value of pointwiseMetricResult field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPointwiseMetricResult() { + return pointwiseMetricResult(Optional.empty()); + } + + /** + * Setter for rougeMetricValue. + * + *

    rougeMetricValue: Results for rouge metric. + */ + @JsonProperty("rougeMetricValue") + public abstract Builder rougeMetricValue(RougeMetricValue rougeMetricValue); + + /** + * Setter for rougeMetricValue builder. + * + *

    rougeMetricValue: Results for rouge metric. + */ + @CanIgnoreReturnValue + public Builder rougeMetricValue(RougeMetricValue.Builder rougeMetricValueBuilder) { + return rougeMetricValue(rougeMetricValueBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder rougeMetricValue(Optional rougeMetricValue); + + /** Clears the value of rougeMetricValue field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearRougeMetricValue() { + return rougeMetricValue(Optional.empty()); + } + + public abstract AggregationResult build(); + } + + /** Deserializes a JSON string to a AggregationResult object. */ + @ExcludeFromGeneratedCoverageReport + public static AggregationResult fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, AggregationResult.class); + } +} diff --git a/src/main/java/com/google/genai/types/ApiAuth.java b/src/main/java/com/google/genai/types/ApiAuth.java new file mode 100644 index 00000000000..bfffc3620fa --- /dev/null +++ b/src/main/java/com/google/genai/types/ApiAuth.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 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; + +/** + * The generic reusable api auth config. Deprecated. Please use AuthConfig + * (google/cloud/aiplatform/master/auth.proto) instead. This data type is not supported in Gemini + * API. + */ +@AutoValue +@JsonDeserialize(builder = ApiAuth.Builder.class) +public abstract class ApiAuth extends JsonSerializable { + /** The API secret. */ + @JsonProperty("apiKeyConfig") + public abstract Optional apiKeyConfig(); + + /** Instantiates a builder for ApiAuth. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ApiAuth.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ApiAuth. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ApiAuth.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ApiAuth.Builder(); + } + + /** + * Setter for apiKeyConfig. + * + *

    apiKeyConfig: The API secret. + */ + @JsonProperty("apiKeyConfig") + public abstract Builder apiKeyConfig(ApiAuthApiKeyConfig apiKeyConfig); + + /** + * Setter for apiKeyConfig builder. + * + *

    apiKeyConfig: The API secret. + */ + @CanIgnoreReturnValue + public Builder apiKeyConfig(ApiAuthApiKeyConfig.Builder apiKeyConfigBuilder) { + return apiKeyConfig(apiKeyConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder apiKeyConfig(Optional apiKeyConfig); + + /** Clears the value of apiKeyConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearApiKeyConfig() { + return apiKeyConfig(Optional.empty()); + } + + public abstract ApiAuth build(); + } + + /** 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 new file mode 100644 index 00000000000..623beda2b0b --- /dev/null +++ b/src/main/java/com/google/genai/types/ApiAuthApiKeyConfig.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. + */ + +// 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; + +/** The API secret. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = ApiAuthApiKeyConfig.Builder.class) +public abstract class ApiAuthApiKeyConfig extends JsonSerializable { + /** + * Required. The SecretManager secret version resource name storing API key. e.g. + * projects/{project}/secrets/{secret}/versions/{version} + */ + @JsonProperty("apiKeySecretVersion") + public abstract Optional apiKeySecretVersion(); + + /** The API key string. Either this or `api_key_secret_version` must be set. */ + @JsonProperty("apiKeyString") + public abstract Optional apiKeyString(); + + /** Instantiates a builder for ApiAuthApiKeyConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ApiAuthApiKeyConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ApiAuthApiKeyConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ApiAuthApiKeyConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ApiAuthApiKeyConfig.Builder(); + } + + /** + * Setter for apiKeySecretVersion. + * + *

    apiKeySecretVersion: Required. The SecretManager secret version resource name storing API + * key. e.g. projects/{project}/secrets/{secret}/versions/{version} + */ + @JsonProperty("apiKeySecretVersion") + public abstract Builder apiKeySecretVersion(String apiKeySecretVersion); + + @ExcludeFromGeneratedCoverageReport + abstract Builder apiKeySecretVersion(Optional apiKeySecretVersion); + + /** Clears the value of apiKeySecretVersion field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearApiKeySecretVersion() { + return apiKeySecretVersion(Optional.empty()); + } + + /** + * Setter for apiKeyString. + * + *

    apiKeyString: The API key string. Either this or `api_key_secret_version` must be set. + */ + @JsonProperty("apiKeyString") + public abstract Builder apiKeyString(String apiKeyString); + + @ExcludeFromGeneratedCoverageReport + abstract Builder apiKeyString(Optional apiKeyString); + + /** Clears the value of apiKeyString field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearApiKeyString() { + return apiKeyString(Optional.empty()); + } + + public abstract ApiAuthApiKeyConfig build(); + } + + /** 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..6bec0020f30 100644 --- a/src/main/java/com/google/genai/types/ApiKeyConfig.java +++ b/src/main/java/com/google/genai/types/ApiKeyConfig.java @@ -22,18 +22,43 @@ 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; -/** Config for authentication with API key. */ +/** Config for authentication with API key. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = ApiKeyConfig.Builder.class) public abstract class ApiKeyConfig extends JsonSerializable { - /** The API key to be used in the request directly. */ + /** + * Optional. The name of the SecretManager secret version resource storing the API key. Format: + * `projects/{project}/secrets/{secrete}/versions/{version}` - If both `api_key_secret` and + * `api_key_string` are specified, this field takes precedence over `api_key_string`. - If + * specified, the `secretmanager.versions.access` permission should be granted to Vertex AI + * Extension Service Agent + * (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the + * specified resource. + */ + @JsonProperty("apiKeySecret") + public abstract Optional apiKeySecret(); + + /** Optional. The API key to be used in the request directly. */ @JsonProperty("apiKeyString") public abstract Optional apiKeyString(); + /** Optional. The location of the API key. */ + @JsonProperty("httpElementLocation") + public abstract Optional httpElementLocation(); + + /** + * Optional. The parameter name of the API key. E.g. If the API request is + * "https://example.com/act?api_key=", "api_key" would be the parameter name. + */ + @JsonProperty("name") + public abstract Optional name(); + /** Instantiates a builder for ApiKeyConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ApiKeyConfig.Builder(); } @@ -50,18 +75,110 @@ private static Builder create() { return new AutoValue_ApiKeyConfig.Builder(); } + /** + * Setter for apiKeySecret. + * + *

    apiKeySecret: Optional. The name of the SecretManager secret version resource storing the + * API key. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If both + * `api_key_secret` and `api_key_string` are specified, this field takes precedence over + * `api_key_string`. - If specified, the `secretmanager.versions.access` permission should be + * granted to Vertex AI Extension Service Agent + * (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the + * specified resource. + */ + @JsonProperty("apiKeySecret") + public abstract Builder apiKeySecret(String apiKeySecret); + + @ExcludeFromGeneratedCoverageReport + abstract Builder apiKeySecret(Optional apiKeySecret); + + /** Clears the value of apiKeySecret field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearApiKeySecret() { + return apiKeySecret(Optional.empty()); + } + /** * Setter for apiKeyString. * - *

    apiKeyString: The API key to be used in the request directly. + *

    apiKeyString: Optional. The API key to be used in the request directly. */ @JsonProperty("apiKeyString") public abstract Builder apiKeyString(String apiKeyString); + @ExcludeFromGeneratedCoverageReport + abstract Builder apiKeyString(Optional apiKeyString); + + /** Clears the value of apiKeyString field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearApiKeyString() { + return apiKeyString(Optional.empty()); + } + + /** + * Setter for httpElementLocation. + * + *

    httpElementLocation: Optional. The location of the API key. + */ + @JsonProperty("httpElementLocation") + public abstract Builder httpElementLocation(HttpElementLocation httpElementLocation); + + @ExcludeFromGeneratedCoverageReport + abstract Builder httpElementLocation(Optional httpElementLocation); + + /** Clears the value of httpElementLocation field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpElementLocation() { + return httpElementLocation(Optional.empty()); + } + + /** + * Setter for httpElementLocation given a known enum. + * + *

    httpElementLocation: Optional. The location of the API key. + */ + @CanIgnoreReturnValue + public Builder httpElementLocation(HttpElementLocation.Known knownType) { + return httpElementLocation(new HttpElementLocation(knownType)); + } + + /** + * Setter for httpElementLocation given a string. + * + *

    httpElementLocation: Optional. The location of the API key. + */ + @CanIgnoreReturnValue + public Builder httpElementLocation(String httpElementLocation) { + return httpElementLocation(new HttpElementLocation(httpElementLocation)); + } + + /** + * Setter for name. + * + *

    name: Optional. The parameter name of the API key. E.g. If the API request is + * "https://example.com/act?api_key=", "api_key" would be the parameter name. + */ + @JsonProperty("name") + public abstract Builder name(String name); + + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + public abstract ApiKeyConfig build(); } /** 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 new file mode 100644 index 00000000000..d52ef5f5a74 --- /dev/null +++ b/src/main/java/com/google/genai/types/ApiSpec.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 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. */ + public enum Known { + /** Unspecified API spec. This value should not be used. */ + API_SPEC_UNSPECIFIED, + + /** Simple search API spec. */ + SIMPLE_SEARCH, + + /** Elastic search API spec. */ + ELASTIC_SEARCH + } + + private Known apiSpecEnum; + private final String value; + + @JsonCreator + public ApiSpec(String value) { + this.value = value; + for (Known apiSpecEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(apiSpecEnum.toString(), value)) { + this.apiSpecEnum = apiSpecEnum; + break; + } + } + if (this.apiSpecEnum == null) { + this.apiSpecEnum = Known.API_SPEC_UNSPECIFIED; + } + } + + public ApiSpec(Known knownValue) { + this.apiSpecEnum = 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 ApiSpec)) { + return false; + } + + ApiSpec other = (ApiSpec) o; + + if (this.apiSpecEnum != Known.API_SPEC_UNSPECIFIED + && other.apiSpecEnum != Known.API_SPEC_UNSPECIFIED) { + return this.apiSpecEnum == other.apiSpecEnum; + } else if (this.apiSpecEnum == Known.API_SPEC_UNSPECIFIED + && other.apiSpecEnum == Known.API_SPEC_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.apiSpecEnum != Known.API_SPEC_UNSPECIFIED) { + return this.apiSpecEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @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..44367c230b0 100644 --- a/src/main/java/com/google/genai/types/AudioTranscriptionConfig.java +++ b/src/main/java/com/google/genai/types/AudioTranscriptionConfig.java @@ -19,15 +19,29 @@ 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; /** The audio transcription configuration in Setup. */ @AutoValue @JsonDeserialize(builder = AudioTranscriptionConfig.Builder.class) public abstract class AudioTranscriptionConfig extends JsonSerializable { + /** + * The language codes of the audio. BCP-47 language code. If not set, the transcription will be in + * the language detected by the model. If set, the server will use the language code specified in + * the model config as a hint for the language of the audio + */ + @JsonProperty("languageCodes") + public abstract Optional> languageCodes(); + /** Instantiates a builder for AudioTranscriptionConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_AudioTranscriptionConfig.Builder(); } @@ -44,10 +58,43 @@ private static Builder create() { return new AutoValue_AudioTranscriptionConfig.Builder(); } + /** + * Setter for languageCodes. + * + *

    languageCodes: The language codes of the audio. BCP-47 language code. If not set, the + * transcription will be in the language detected by the model. If set, the server will use the + * language code specified in the model config as a hint for the language of the audio + */ + @JsonProperty("languageCodes") + public abstract Builder languageCodes(List languageCodes); + + /** + * Setter for languageCodes. + * + *

    languageCodes: The language codes of the audio. BCP-47 language code. If not set, the + * transcription will be in the language detected by the model. If set, the server will use the + * language code specified in the model config as a hint for the language of the audio + */ + @CanIgnoreReturnValue + public Builder languageCodes(String... languageCodes) { + return languageCodes(Arrays.asList(languageCodes)); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder languageCodes(Optional> languageCodes); + + /** Clears the value of languageCodes field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLanguageCodes() { + return languageCodes(Optional.empty()); + } + public abstract AudioTranscriptionConfig build(); } /** 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 e3c371b34a5..82c66ea34e2 100644 --- a/src/main/java/com/google/genai/types/AuthConfig.java +++ b/src/main/java/com/google/genai/types/AuthConfig.java @@ -26,10 +26,17 @@ import com.google.genai.JsonSerializable; import java.util.Optional; -/** Auth configuration to run the extension. */ +/** The authentication config to access the API. */ @AutoValue @JsonDeserialize(builder = AuthConfig.Builder.class) public abstract class AuthConfig extends JsonSerializable { + /** + * The authentication config to access the API. Only API key is supported. This field is not + * supported in Gemini API. + */ + @JsonProperty("apiKey") + public abstract Optional apiKey(); + /** Config for API key auth. */ @JsonProperty("apiKeyConfig") public abstract Optional apiKeyConfig(); @@ -55,6 +62,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(); } @@ -71,6 +79,25 @@ private static Builder create() { return new AutoValue_AuthConfig.Builder(); } + /** + * Setter for apiKey. + * + *

    apiKey: The authentication config to access the API. Only API key is supported. This field + * is not supported in Gemini API. + */ + @JsonProperty("apiKey") + public abstract Builder apiKey(String apiKey); + + @ExcludeFromGeneratedCoverageReport + abstract Builder apiKey(Optional apiKey); + + /** Clears the value of apiKey field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearApiKey() { + return apiKey(Optional.empty()); + } + /** * Setter for apiKeyConfig. * @@ -84,10 +111,21 @@ private static Builder create() { * *

    apiKeyConfig: Config for API key auth. */ + @CanIgnoreReturnValue public Builder apiKeyConfig(ApiKeyConfig.Builder apiKeyConfigBuilder) { return apiKeyConfig(apiKeyConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder apiKeyConfig(Optional apiKeyConfig); + + /** Clears the value of apiKeyConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearApiKeyConfig() { + return apiKeyConfig(Optional.empty()); + } + /** * Setter for authType. * @@ -96,21 +134,41 @@ public Builder apiKeyConfig(ApiKeyConfig.Builder apiKeyConfigBuilder) { @JsonProperty("authType") public abstract Builder authType(AuthType authType); + @ExcludeFromGeneratedCoverageReport + abstract Builder authType(Optional authType); + + /** Clears the value of authType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAuthType() { + return authType(Optional.empty()); + } + + /** + * Setter for authType given a known enum. + * + *

    authType: Type of auth scheme. + */ @CanIgnoreReturnValue public Builder authType(AuthType.Known knownType) { return authType(new AuthType(knownType)); } + /** + * Setter for authType given a string. + * + *

    authType: Type of auth scheme. + */ @CanIgnoreReturnValue public Builder authType(String authType) { return authType(new AuthType(authType)); } + /** * Setter for googleServiceAccountConfig. * *

    googleServiceAccountConfig: Config for Google Service Account auth. */ - @JsonProperty("googleServiceAccountConfig") public abstract Builder googleServiceAccountConfig( AuthConfigGoogleServiceAccountConfig googleServiceAccountConfig); @@ -120,11 +178,23 @@ public abstract Builder googleServiceAccountConfig( * *

    googleServiceAccountConfig: Config for Google Service Account auth. */ + @CanIgnoreReturnValue public Builder googleServiceAccountConfig( AuthConfigGoogleServiceAccountConfig.Builder googleServiceAccountConfigBuilder) { return googleServiceAccountConfig(googleServiceAccountConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder googleServiceAccountConfig( + Optional googleServiceAccountConfig); + + /** Clears the value of googleServiceAccountConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGoogleServiceAccountConfig() { + return googleServiceAccountConfig(Optional.empty()); + } + /** * Setter for httpBasicAuthConfig. * @@ -138,11 +208,23 @@ public Builder googleServiceAccountConfig( * *

    httpBasicAuthConfig: Config for HTTP Basic auth. */ + @CanIgnoreReturnValue public Builder httpBasicAuthConfig( AuthConfigHttpBasicAuthConfig.Builder httpBasicAuthConfigBuilder) { return httpBasicAuthConfig(httpBasicAuthConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpBasicAuthConfig( + Optional httpBasicAuthConfig); + + /** Clears the value of httpBasicAuthConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpBasicAuthConfig() { + return httpBasicAuthConfig(Optional.empty()); + } + /** * Setter for oauthConfig. * @@ -156,10 +238,21 @@ public Builder httpBasicAuthConfig( * *

    oauthConfig: Config for user oauth. */ + @CanIgnoreReturnValue public Builder oauthConfig(AuthConfigOauthConfig.Builder oauthConfigBuilder) { return oauthConfig(oauthConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder oauthConfig(Optional oauthConfig); + + /** Clears the value of oauthConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOauthConfig() { + return oauthConfig(Optional.empty()); + } + /** * Setter for oidcConfig. * @@ -173,14 +266,26 @@ public Builder oauthConfig(AuthConfigOauthConfig.Builder oauthConfigBuilder) { * *

    oidcConfig: Config for user OIDC auth. */ + @CanIgnoreReturnValue public Builder oidcConfig(AuthConfigOidcConfig.Builder oidcConfigBuilder) { return oidcConfig(oidcConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder oidcConfig(Optional oidcConfig); + + /** Clears the value of oidcConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOidcConfig() { + return oidcConfig(Optional.empty()); + } + public abstract AuthConfig build(); } /** 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..d8b05dd1ac1 100644 --- a/src/main/java/com/google/genai/types/AuthConfigGoogleServiceAccountConfig.java +++ b/src/main/java/com/google/genai/types/AuthConfigGoogleServiceAccountConfig.java @@ -22,10 +22,13 @@ 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; -/** 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 +44,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(); } @@ -73,10 +77,21 @@ private static Builder create() { @JsonProperty("serviceAccount") public abstract Builder serviceAccount(String serviceAccount); + @ExcludeFromGeneratedCoverageReport + abstract Builder serviceAccount(Optional serviceAccount); + + /** Clears the value of serviceAccount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearServiceAccount() { + return serviceAccount(Optional.empty()); + } + public abstract AuthConfigGoogleServiceAccountConfig build(); } /** 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..e5a266c7db9 100644 --- a/src/main/java/com/google/genai/types/AuthConfigHttpBasicAuthConfig.java +++ b/src/main/java/com/google/genai/types/AuthConfigHttpBasicAuthConfig.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; -/** 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 +41,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(); } @@ -71,10 +73,21 @@ private static Builder create() { @JsonProperty("credentialSecret") public abstract Builder credentialSecret(String credentialSecret); + @ExcludeFromGeneratedCoverageReport + abstract Builder credentialSecret(Optional credentialSecret); + + /** Clears the value of credentialSecret field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCredentialSecret() { + return credentialSecret(Optional.empty()); + } + public abstract AuthConfigHttpBasicAuthConfig build(); } /** 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..35ce227a30b 100644 --- a/src/main/java/com/google/genai/types/AuthConfigOauthConfig.java +++ b/src/main/java/com/google/genai/types/AuthConfigOauthConfig.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; -/** 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 +48,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(); } @@ -72,6 +74,16 @@ private static Builder create() { @JsonProperty("accessToken") public abstract Builder accessToken(String accessToken); + @ExcludeFromGeneratedCoverageReport + abstract Builder accessToken(Optional accessToken); + + /** Clears the value of accessToken field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAccessToken() { + return accessToken(Optional.empty()); + } + /** * Setter for serviceAccount. * @@ -84,10 +96,21 @@ private static Builder create() { @JsonProperty("serviceAccount") public abstract Builder serviceAccount(String serviceAccount); + @ExcludeFromGeneratedCoverageReport + abstract Builder serviceAccount(Optional serviceAccount); + + /** Clears the value of serviceAccount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearServiceAccount() { + return serviceAccount(Optional.empty()); + } + public abstract AuthConfigOauthConfig build(); } /** 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..2572aa1581d 100644 --- a/src/main/java/com/google/genai/types/AuthConfigOidcConfig.java +++ b/src/main/java/com/google/genai/types/AuthConfigOidcConfig.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; -/** 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 +50,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(); } @@ -74,6 +76,16 @@ private static Builder create() { @JsonProperty("idToken") public abstract Builder idToken(String idToken); + @ExcludeFromGeneratedCoverageReport + abstract Builder idToken(Optional idToken); + + /** Clears the value of idToken field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearIdToken() { + return idToken(Optional.empty()); + } + /** * Setter for serviceAccount. * @@ -88,10 +100,21 @@ private static Builder create() { @JsonProperty("serviceAccount") public abstract Builder serviceAccount(String serviceAccount); + @ExcludeFromGeneratedCoverageReport + abstract Builder serviceAccount(Optional serviceAccount); + + /** Clears the value of serviceAccount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearServiceAccount() { + return serviceAccount(Optional.empty()); + } + public abstract AuthConfigOidcConfig build(); } /** 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/AuthToken.java b/src/main/java/com/google/genai/types/AuthToken.java index 444f1d5e1d9..f97f6821bac 100644 --- a/src/main/java/com/google/genai/types/AuthToken.java +++ b/src/main/java/com/google/genai/types/AuthToken.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; @@ -34,6 +35,7 @@ public abstract class AuthToken extends JsonSerializable { public abstract Optional name(); /** Instantiates a builder for AuthToken. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_AuthToken.Builder(); } @@ -50,13 +52,29 @@ private static Builder create() { return new AutoValue_AuthToken.Builder(); } + /** + * Setter for name. + * + *

    name: The name of the auth token. + */ @JsonProperty("name") public abstract Builder name(String name); + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + public abstract AuthToken build(); } /** Deserializes a JSON string to a AuthToken object. */ + @ExcludeFromGeneratedCoverageReport public static AuthToken fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, AuthToken.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 62a06907b4e..5fee77a7f9b 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(); } @@ -87,6 +88,16 @@ private static Builder create() { @JsonProperty("disabled") public abstract Builder disabled(boolean disabled); + @ExcludeFromGeneratedCoverageReport + abstract Builder disabled(Optional disabled); + + /** Clears the value of disabled field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisabled() { + return disabled(Optional.empty()); + } + /** * Setter for startOfSpeechSensitivity. * @@ -95,33 +106,74 @@ private static Builder create() { @JsonProperty("startOfSpeechSensitivity") public abstract Builder startOfSpeechSensitivity(StartSensitivity startOfSpeechSensitivity); + @ExcludeFromGeneratedCoverageReport + abstract Builder startOfSpeechSensitivity(Optional startOfSpeechSensitivity); + + /** Clears the value of startOfSpeechSensitivity field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearStartOfSpeechSensitivity() { + return startOfSpeechSensitivity(Optional.empty()); + } + + /** + * Setter for startOfSpeechSensitivity given a known enum. + * + *

    startOfSpeechSensitivity: Determines how likely speech is to be detected. + */ @CanIgnoreReturnValue public Builder startOfSpeechSensitivity(StartSensitivity.Known knownType) { return startOfSpeechSensitivity(new StartSensitivity(knownType)); } + /** + * Setter for startOfSpeechSensitivity given a string. + * + *

    startOfSpeechSensitivity: Determines how likely speech is to be detected. + */ @CanIgnoreReturnValue public Builder startOfSpeechSensitivity(String startOfSpeechSensitivity) { return startOfSpeechSensitivity(new StartSensitivity(startOfSpeechSensitivity)); } + /** * Setter for endOfSpeechSensitivity. * *

    endOfSpeechSensitivity: Determines how likely detected speech is ended. */ - @JsonProperty("endOfSpeechSensitivity") public abstract Builder endOfSpeechSensitivity(EndSensitivity endOfSpeechSensitivity); + @ExcludeFromGeneratedCoverageReport + abstract Builder endOfSpeechSensitivity(Optional endOfSpeechSensitivity); + + /** Clears the value of endOfSpeechSensitivity field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEndOfSpeechSensitivity() { + return endOfSpeechSensitivity(Optional.empty()); + } + + /** + * Setter for endOfSpeechSensitivity given a known enum. + * + *

    endOfSpeechSensitivity: Determines how likely detected speech is ended. + */ @CanIgnoreReturnValue public Builder endOfSpeechSensitivity(EndSensitivity.Known knownType) { return endOfSpeechSensitivity(new EndSensitivity(knownType)); } + /** + * Setter for endOfSpeechSensitivity given a string. + * + *

    endOfSpeechSensitivity: Determines how likely detected speech is ended. + */ @CanIgnoreReturnValue public Builder endOfSpeechSensitivity(String endOfSpeechSensitivity) { return endOfSpeechSensitivity(new EndSensitivity(endOfSpeechSensitivity)); } + /** * Setter for prefixPaddingMs. * @@ -130,10 +182,19 @@ public Builder endOfSpeechSensitivity(String endOfSpeechSensitivity) { * shorter speech can be recognized. However, this also increases the probability of false * positives. */ - @JsonProperty("prefixPaddingMs") public abstract Builder prefixPaddingMs(Integer prefixPaddingMs); + @ExcludeFromGeneratedCoverageReport + abstract Builder prefixPaddingMs(Optional prefixPaddingMs); + + /** Clears the value of prefixPaddingMs field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPrefixPaddingMs() { + return prefixPaddingMs(Optional.empty()); + } + /** * Setter for silenceDurationMs. * @@ -144,10 +205,21 @@ public Builder endOfSpeechSensitivity(String endOfSpeechSensitivity) { @JsonProperty("silenceDurationMs") public abstract Builder silenceDurationMs(Integer silenceDurationMs); + @ExcludeFromGeneratedCoverageReport + abstract Builder silenceDurationMs(Optional silenceDurationMs); + + /** Clears the value of silenceDurationMs field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSilenceDurationMs() { + return silenceDurationMs(Optional.empty()); + } + public abstract AutomaticActivityDetection build(); } /** 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..70a86eb0cab 100644 --- a/src/main/java/com/google/genai/types/AutomaticFunctionCallingConfig.java +++ b/src/main/java/com/google/genai/types/AutomaticFunctionCallingConfig.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; @@ -53,6 +54,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(); } @@ -80,6 +82,16 @@ private static Builder create() { @JsonProperty("disable") public abstract Builder disable(boolean disable); + @ExcludeFromGeneratedCoverageReport + abstract Builder disable(Optional disable); + + /** Clears the value of disable field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisable() { + return disable(Optional.empty()); + } + /** * Setter for maximumRemoteCalls. * @@ -90,6 +102,16 @@ private static Builder create() { @JsonProperty("maximumRemoteCalls") public abstract Builder maximumRemoteCalls(Integer maximumRemoteCalls); + @ExcludeFromGeneratedCoverageReport + abstract Builder maximumRemoteCalls(Optional maximumRemoteCalls); + + /** Clears the value of maximumRemoteCalls field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMaximumRemoteCalls() { + return maximumRemoteCalls(Optional.empty()); + } + /** * Setter for ignoreCallHistory. * @@ -100,10 +122,21 @@ private static Builder create() { @JsonProperty("ignoreCallHistory") public abstract Builder ignoreCallHistory(boolean ignoreCallHistory); + @ExcludeFromGeneratedCoverageReport + abstract Builder ignoreCallHistory(Optional ignoreCallHistory); + + /** Clears the value of ignoreCallHistory field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearIgnoreCallHistory() { + return ignoreCallHistory(Optional.empty()); + } + public abstract AutomaticFunctionCallingConfig build(); } /** 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/AutoraterConfig.java b/src/main/java/com/google/genai/types/AutoraterConfig.java new file mode 100644 index 00000000000..fb260aa7b3f --- /dev/null +++ b/src/main/java/com/google/genai/types/AutoraterConfig.java @@ -0,0 +1,153 @@ +/* + * 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; + +/** Autorater config used for evaluation. */ +@AutoValue +@JsonDeserialize(builder = AutoraterConfig.Builder.class) +public abstract class AutoraterConfig extends JsonSerializable { + /** + * Number of samples for each instance in the dataset. If not specified, the default is 4. Minimum + * value is 1, maximum value is 32. + */ + @JsonProperty("samplingCount") + public abstract Optional samplingCount(); + + /** + * The fully qualified name of the publisher model or tuned autorater endpoint to use. + * + *

    Publisher model format: + * `projects/{project}/locations/{location}/publishers/{publisher}/models/{model}` + * + *

    Tuned model endpoint format: `projects/{project}/locations/{location}/endpoints/{endpoint}` + */ + @JsonProperty("autoraterModel") + public abstract Optional autoraterModel(); + + /** Configuration options for model generation and outputs. */ + @JsonProperty("generationConfig") + public abstract Optional generationConfig(); + + /** Instantiates a builder for AutoraterConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_AutoraterConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for AutoraterConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `AutoraterConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_AutoraterConfig.Builder(); + } + + /** + * Setter for samplingCount. + * + *

    samplingCount: Number of samples for each instance in the dataset. If not specified, the + * default is 4. Minimum value is 1, maximum value is 32. + */ + @JsonProperty("samplingCount") + public abstract Builder samplingCount(Integer samplingCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder samplingCount(Optional samplingCount); + + /** Clears the value of samplingCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSamplingCount() { + return samplingCount(Optional.empty()); + } + + /** + * Setter for autoraterModel. + * + *

    autoraterModel: The fully qualified name of the publisher model or tuned autorater + * endpoint to use. + * + *

    Publisher model format: + * `projects/{project}/locations/{location}/publishers/{publisher}/models/{model}` + * + *

    Tuned model endpoint format: + * `projects/{project}/locations/{location}/endpoints/{endpoint}` + */ + @JsonProperty("autoraterModel") + public abstract Builder autoraterModel(String autoraterModel); + + @ExcludeFromGeneratedCoverageReport + abstract Builder autoraterModel(Optional autoraterModel); + + /** Clears the value of autoraterModel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAutoraterModel() { + return autoraterModel(Optional.empty()); + } + + /** + * Setter for generationConfig. + * + *

    generationConfig: Configuration options for model generation and outputs. + */ + @JsonProperty("generationConfig") + public abstract Builder generationConfig(GenerationConfig generationConfig); + + /** + * Setter for generationConfig builder. + * + *

    generationConfig: Configuration options for model generation and outputs. + */ + @CanIgnoreReturnValue + public Builder generationConfig(GenerationConfig.Builder generationConfigBuilder) { + return generationConfig(generationConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder generationConfig(Optional generationConfig); + + /** Clears the value of generationConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGenerationConfig() { + return generationConfig(Optional.empty()); + } + + public abstract AutoraterConfig build(); + } + + /** Deserializes a JSON string to a AutoraterConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static AutoraterConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, AutoraterConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/AvatarConfig.java b/src/main/java/com/google/genai/types/AvatarConfig.java new file mode 100644 index 00000000000..e9a6005b216 --- /dev/null +++ b/src/main/java/com/google/genai/types/AvatarConfig.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. + */ + +// 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; + +/** Configures the avatar to be used in the session. */ +@AutoValue +@JsonDeserialize(builder = AvatarConfig.Builder.class) +public abstract class AvatarConfig extends JsonSerializable { + /** Pre-built avatar id. */ + @JsonProperty("avatarName") + public abstract Optional avatarName(); + + /** Customized avatar appearance with a reference image. */ + @JsonProperty("customizedAvatar") + public abstract Optional customizedAvatar(); + + /** The bitrate of compressed audio. */ + @JsonProperty("audioBitrateBps") + public abstract Optional audioBitrateBps(); + + /** The bitrate of compressed video output. */ + @JsonProperty("videoBitrateBps") + public abstract Optional videoBitrateBps(); + + /** Instantiates a builder for AvatarConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_AvatarConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for AvatarConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `AvatarConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_AvatarConfig.Builder(); + } + + /** + * Setter for avatarName. + * + *

    avatarName: Pre-built avatar id. + */ + @JsonProperty("avatarName") + public abstract Builder avatarName(String avatarName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder avatarName(Optional avatarName); + + /** Clears the value of avatarName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAvatarName() { + return avatarName(Optional.empty()); + } + + /** + * Setter for customizedAvatar. + * + *

    customizedAvatar: Customized avatar appearance with a reference image. + */ + @JsonProperty("customizedAvatar") + public abstract Builder customizedAvatar(CustomizedAvatar customizedAvatar); + + /** + * Setter for customizedAvatar builder. + * + *

    customizedAvatar: Customized avatar appearance with a reference image. + */ + @CanIgnoreReturnValue + public Builder customizedAvatar(CustomizedAvatar.Builder customizedAvatarBuilder) { + return customizedAvatar(customizedAvatarBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder customizedAvatar(Optional customizedAvatar); + + /** Clears the value of customizedAvatar field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCustomizedAvatar() { + return customizedAvatar(Optional.empty()); + } + + /** + * Setter for audioBitrateBps. + * + *

    audioBitrateBps: The bitrate of compressed audio. + */ + @JsonProperty("audioBitrateBps") + public abstract Builder audioBitrateBps(Integer audioBitrateBps); + + @ExcludeFromGeneratedCoverageReport + abstract Builder audioBitrateBps(Optional audioBitrateBps); + + /** Clears the value of audioBitrateBps field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAudioBitrateBps() { + return audioBitrateBps(Optional.empty()); + } + + /** + * Setter for videoBitrateBps. + * + *

    videoBitrateBps: The bitrate of compressed video output. + */ + @JsonProperty("videoBitrateBps") + public abstract Builder videoBitrateBps(Integer videoBitrateBps); + + @ExcludeFromGeneratedCoverageReport + abstract Builder videoBitrateBps(Optional videoBitrateBps); + + /** Clears the value of videoBitrateBps field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearVideoBitrateBps() { + return videoBitrateBps(Optional.empty()); + } + + public abstract AvatarConfig build(); + } + + /** Deserializes a JSON string to a AvatarConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static AvatarConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, AvatarConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/BatchJob.java b/src/main/java/com/google/genai/types/BatchJob.java new file mode 100644 index 00000000000..aabeb9dc9a5 --- /dev/null +++ b/src/main/java/com/google/genai/types/BatchJob.java @@ -0,0 +1,432 @@ +/* + * 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.time.Instant; +import java.util.Optional; + +/** Config for batches.create return value. */ +@AutoValue +@JsonDeserialize(builder = BatchJob.Builder.class) +public abstract class BatchJob extends JsonSerializable { + /** The resource name of the BatchJob. Output only.". */ + @JsonProperty("name") + public abstract Optional name(); + + /** The display name of the BatchJob. */ + @JsonProperty("displayName") + public abstract Optional displayName(); + + /** The state of the BatchJob. */ + @JsonProperty("state") + public abstract Optional state(); + + /** + * Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. + */ + @JsonProperty("error") + public abstract Optional error(); + + /** The time when the BatchJob was created. */ + @JsonProperty("createTime") + public abstract Optional createTime(); + + /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */ + @JsonProperty("startTime") + public abstract Optional startTime(); + + /** + * The time when the BatchJob was completed. This field is for Gemini Enterprise Agent Platform + * only. + */ + @JsonProperty("endTime") + public abstract Optional endTime(); + + /** The time when the BatchJob was last updated. */ + @JsonProperty("updateTime") + public abstract Optional updateTime(); + + /** The name of the model that produces the predictions via the BatchJob. */ + @JsonProperty("model") + public abstract Optional model(); + + /** Configuration for the input data. This field is for Gemini Enterprise Agent Platform only. */ + @JsonProperty("src") + public abstract Optional src(); + + /** Configuration for the output data. */ + @JsonProperty("dest") + public abstract Optional dest(); + + /** + * Statistics on completed and failed prediction instances. This field is for Gemini Enterprise + * Agent Platform only. + */ + @JsonProperty("completionStats") + public abstract Optional completionStats(); + + /** Information further describing the output of this job. Output only. */ + @JsonProperty("outputInfo") + public abstract Optional outputInfo(); + + /** Instantiates a builder for BatchJob. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_BatchJob.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for BatchJob. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `BatchJob.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_BatchJob.Builder(); + } + + /** + * Setter for name. + * + *

    name: The resource name of the BatchJob. Output only.". + */ + @JsonProperty("name") + public abstract Builder name(String name); + + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + + /** + * Setter for displayName. + * + *

    displayName: The display name of the BatchJob. + */ + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + + /** + * Setter for state. + * + *

    state: The state of the BatchJob. + */ + @JsonProperty("state") + public abstract Builder state(JobState state); + + @ExcludeFromGeneratedCoverageReport + abstract Builder state(Optional state); + + /** Clears the value of state field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearState() { + return state(Optional.empty()); + } + + /** + * Setter for state given a known enum. + * + *

    state: The state of the BatchJob. + */ + @CanIgnoreReturnValue + public Builder state(JobState.Known knownType) { + return state(new JobState(knownType)); + } + + /** + * Setter for state given a string. + * + *

    state: The state of the BatchJob. + */ + @CanIgnoreReturnValue + public Builder state(String state) { + return state(new JobState(state)); + } + + /** + * Setter for error. + * + *

    error: Output only. Only populated when the job's state is JOB_STATE_FAILED or + * JOB_STATE_CANCELLED. + */ + @JsonProperty("error") + public abstract Builder error(JobError error); + + /** + * Setter for error builder. + * + *

    error: Output only. Only populated when the job's state is JOB_STATE_FAILED or + * JOB_STATE_CANCELLED. + */ + @CanIgnoreReturnValue + public Builder error(JobError.Builder errorBuilder) { + return error(errorBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder error(Optional error); + + /** Clears the value of error field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearError() { + return error(Optional.empty()); + } + + /** + * Setter for createTime. + * + *

    createTime: The time when the BatchJob was created. + */ + @JsonProperty("createTime") + public abstract Builder createTime(Instant createTime); + + @ExcludeFromGeneratedCoverageReport + abstract Builder createTime(Optional createTime); + + /** Clears the value of createTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCreateTime() { + return createTime(Optional.empty()); + } + + /** + * Setter for startTime. + * + *

    startTime: Output only. Time when the Job for the first time entered the + * `JOB_STATE_RUNNING` state. + */ + @JsonProperty("startTime") + public abstract Builder startTime(Instant startTime); + + @ExcludeFromGeneratedCoverageReport + abstract Builder startTime(Optional startTime); + + /** Clears the value of startTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearStartTime() { + return startTime(Optional.empty()); + } + + /** + * Setter for endTime. + * + *

    endTime: The time when the BatchJob was completed. This field is for Gemini Enterprise + * Agent Platform only. + */ + @JsonProperty("endTime") + public abstract Builder endTime(Instant endTime); + + @ExcludeFromGeneratedCoverageReport + abstract Builder endTime(Optional endTime); + + /** Clears the value of endTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEndTime() { + return endTime(Optional.empty()); + } + + /** + * Setter for updateTime. + * + *

    updateTime: The time when the BatchJob was last updated. + */ + @JsonProperty("updateTime") + public abstract Builder updateTime(Instant updateTime); + + @ExcludeFromGeneratedCoverageReport + abstract Builder updateTime(Optional updateTime); + + /** Clears the value of updateTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUpdateTime() { + return updateTime(Optional.empty()); + } + + /** + * Setter for model. + * + *

    model: The name of the model that produces the predictions via the BatchJob. + */ + @JsonProperty("model") + public abstract Builder model(String model); + + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + + /** + * Setter for src. + * + *

    src: Configuration for the input data. This field is for Gemini Enterprise Agent Platform + * only. + */ + @JsonProperty("src") + public abstract Builder src(BatchJobSource src); + + /** + * Setter for src builder. + * + *

    src: Configuration for the input data. This field is for Gemini Enterprise Agent Platform + * only. + */ + @CanIgnoreReturnValue + public Builder src(BatchJobSource.Builder srcBuilder) { + return src(srcBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder src(Optional src); + + /** Clears the value of src field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSrc() { + return src(Optional.empty()); + } + + /** + * Setter for dest. + * + *

    dest: Configuration for the output data. + */ + @JsonProperty("dest") + public abstract Builder dest(BatchJobDestination dest); + + /** + * Setter for dest builder. + * + *

    dest: Configuration for the output data. + */ + @CanIgnoreReturnValue + public Builder dest(BatchJobDestination.Builder destBuilder) { + return dest(destBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder dest(Optional dest); + + /** Clears the value of dest field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDest() { + return dest(Optional.empty()); + } + + /** + * Setter for completionStats. + * + *

    completionStats: Statistics on completed and failed prediction instances. This field is + * for Gemini Enterprise Agent Platform only. + */ + @JsonProperty("completionStats") + public abstract Builder completionStats(CompletionStats completionStats); + + /** + * Setter for completionStats builder. + * + *

    completionStats: Statistics on completed and failed prediction instances. This field is + * for Gemini Enterprise Agent Platform only. + */ + @CanIgnoreReturnValue + public Builder completionStats(CompletionStats.Builder completionStatsBuilder) { + return completionStats(completionStatsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder completionStats(Optional completionStats); + + /** Clears the value of completionStats field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCompletionStats() { + return completionStats(Optional.empty()); + } + + /** + * Setter for outputInfo. + * + *

    outputInfo: Information further describing the output of this job. Output only. + */ + @JsonProperty("outputInfo") + public abstract Builder outputInfo(BatchJobOutputInfo outputInfo); + + /** + * Setter for outputInfo builder. + * + *

    outputInfo: Information further describing the output of this job. Output only. + */ + @CanIgnoreReturnValue + public Builder outputInfo(BatchJobOutputInfo.Builder outputInfoBuilder) { + return outputInfo(outputInfoBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder outputInfo(Optional outputInfo); + + /** Clears the value of outputInfo field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputInfo() { + return outputInfo(Optional.empty()); + } + + public abstract BatchJob build(); + } + + /** 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 new file mode 100644 index 00000000000..350bc232dde --- /dev/null +++ b/src/main/java/com/google/genai/types/BatchJobDestination.java @@ -0,0 +1,306 @@ +/* + * 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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** Config for `des` parameter. */ +@AutoValue +@JsonDeserialize(builder = BatchJobDestination.Builder.class) +public abstract class BatchJobDestination extends JsonSerializable { + /** Storage format of the output files. Must be one of: 'jsonl', 'bigquery', 'vertex-dataset'. */ + @JsonProperty("format") + public abstract Optional format(); + + /** The Google Cloud Storage URI to the output file. */ + @JsonProperty("gcsUri") + public abstract Optional gcsUri(); + + /** The BigQuery URI to the output table. */ + @JsonProperty("bigqueryUri") + public abstract Optional bigqueryUri(); + + /** + * The Gemini Developer API's file resource name of the output data (e.g. "files/12345"). The file + * will be a JSONL file with a single response per line. The responses will be + * GenerateContentResponse messages formatted as JSON. The responses will be written in the same + * order as the input requests. + */ + @JsonProperty("fileName") + public abstract Optional fileName(); + + /** + * 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("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(); + + /** + * This field is experimental and may change in future versions. The Vertex AI dataset + * destination. + */ + @JsonProperty("vertexDataset") + public abstract Optional vertexDataset(); + + /** Instantiates a builder for BatchJobDestination. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_BatchJobDestination.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for BatchJobDestination. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `BatchJobDestination.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_BatchJobDestination.Builder(); + } + + /** + * Setter for format. + * + *

    format: Storage format of the output files. Must be one of: 'jsonl', 'bigquery', + * 'vertex-dataset'. + */ + @JsonProperty("format") + public abstract Builder format(String format); + + @ExcludeFromGeneratedCoverageReport + abstract Builder format(Optional format); + + /** Clears the value of format field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFormat() { + return format(Optional.empty()); + } + + /** + * Setter for gcsUri. + * + *

    gcsUri: The Google Cloud Storage URI to the output file. + */ + @JsonProperty("gcsUri") + public abstract Builder gcsUri(String gcsUri); + + @ExcludeFromGeneratedCoverageReport + abstract Builder gcsUri(Optional gcsUri); + + /** Clears the value of gcsUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGcsUri() { + return gcsUri(Optional.empty()); + } + + /** + * Setter for bigqueryUri. + * + *

    bigqueryUri: The BigQuery URI to the output table. + */ + @JsonProperty("bigqueryUri") + public abstract Builder bigqueryUri(String bigqueryUri); + + @ExcludeFromGeneratedCoverageReport + abstract Builder bigqueryUri(Optional bigqueryUri); + + /** Clears the value of bigqueryUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBigqueryUri() { + return bigqueryUri(Optional.empty()); + } + + /** + * Setter for fileName. + * + *

    fileName: The Gemini Developer API's file resource name of the output data (e.g. + * "files/12345"). The file will be a JSONL file with a single response per line. The responses + * will be GenerateContentResponse messages formatted as JSON. The responses will be written in + * the same order as the input requests. + */ + @JsonProperty("fileName") + public abstract Builder fileName(String fileName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder fileName(Optional fileName); + + /** Clears the value of fileName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFileName() { + return fileName(Optional.empty()); + } + + /** + * Setter for inlinedResponses. + * + *

    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("inlinedResponses") + public abstract Builder inlinedResponses(List inlinedResponses); + + /** + * Setter for inlinedResponses. + * + *

    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. + */ + @CanIgnoreReturnValue + public Builder inlinedResponses(InlinedResponse... inlinedResponses) { + return inlinedResponses(Arrays.asList(inlinedResponses)); + } + + /** + * Setter for inlinedResponses builder. + * + *

    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. + */ + @CanIgnoreReturnValue + public Builder inlinedResponses(InlinedResponse.Builder... inlinedResponsesBuilders) { + return inlinedResponses( + Arrays.asList(inlinedResponsesBuilders).stream() + .map(InlinedResponse.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder inlinedResponses(Optional> inlinedResponses); + + /** Clears the value of inlinedResponses field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearInlinedResponses() { + return inlinedResponses(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + 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. + */ + @CanIgnoreReturnValue + public Builder inlinedEmbedContentResponses( + InlinedEmbedContentResponse.Builder... inlinedEmbedContentResponsesBuilders) { + return inlinedEmbedContentResponses( + Arrays.asList(inlinedEmbedContentResponsesBuilders).stream() + .map(InlinedEmbedContentResponse.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder inlinedEmbedContentResponses( + Optional> inlinedEmbedContentResponses); + + /** Clears the value of inlinedEmbedContentResponses field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearInlinedEmbedContentResponses() { + return inlinedEmbedContentResponses(Optional.empty()); + } + + /** + * Setter for vertexDataset. + * + *

    vertexDataset: This field is experimental and may change in future versions. The Vertex AI + * dataset destination. + */ + @JsonProperty("vertexDataset") + public abstract Builder vertexDataset(VertexMultimodalDatasetDestination vertexDataset); + + /** + * Setter for vertexDataset builder. + * + *

    vertexDataset: This field is experimental and may change in future versions. The Vertex AI + * dataset destination. + */ + @CanIgnoreReturnValue + public Builder vertexDataset(VertexMultimodalDatasetDestination.Builder vertexDatasetBuilder) { + return vertexDataset(vertexDatasetBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder vertexDataset(Optional vertexDataset); + + /** Clears the value of vertexDataset field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearVertexDataset() { + return vertexDataset(Optional.empty()); + } + + 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/BatchJobOutputInfo.java b/src/main/java/com/google/genai/types/BatchJobOutputInfo.java new file mode 100644 index 00000000000..16bf34eebbe --- /dev/null +++ b/src/main/java/com/google/genai/types/BatchJobOutputInfo.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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Represents the `output_info` field in batch jobs. */ +@AutoValue +@JsonDeserialize(builder = BatchJobOutputInfo.Builder.class) +public abstract class BatchJobOutputInfo extends JsonSerializable { + /** + * This field is experimental and may change in future versions. The Vertex AI dataset name + * containing the output data. + */ + @JsonProperty("vertexMultimodalDatasetName") + public abstract Optional vertexMultimodalDatasetName(); + + /** + * The full path of the Cloud Storage directory created, into which the prediction output is + * written. + */ + @JsonProperty("gcsOutputDirectory") + public abstract Optional gcsOutputDirectory(); + + /** + * The name of the BigQuery table created, in `predictions_` format, into which the + * prediction output is written. + */ + @JsonProperty("bigqueryOutputTable") + public abstract Optional bigqueryOutputTable(); + + /** Instantiates a builder for BatchJobOutputInfo. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_BatchJobOutputInfo.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for BatchJobOutputInfo. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `BatchJobOutputInfo.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_BatchJobOutputInfo.Builder(); + } + + /** + * Setter for vertexMultimodalDatasetName. + * + *

    vertexMultimodalDatasetName: This field is experimental and may change in future versions. + * The Vertex AI dataset name containing the output data. + */ + @JsonProperty("vertexMultimodalDatasetName") + public abstract Builder vertexMultimodalDatasetName(String vertexMultimodalDatasetName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder vertexMultimodalDatasetName(Optional vertexMultimodalDatasetName); + + /** Clears the value of vertexMultimodalDatasetName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearVertexMultimodalDatasetName() { + return vertexMultimodalDatasetName(Optional.empty()); + } + + /** + * Setter for gcsOutputDirectory. + * + *

    gcsOutputDirectory: The full path of the Cloud Storage directory created, into which the + * prediction output is written. + */ + @JsonProperty("gcsOutputDirectory") + public abstract Builder gcsOutputDirectory(String gcsOutputDirectory); + + @ExcludeFromGeneratedCoverageReport + abstract Builder gcsOutputDirectory(Optional gcsOutputDirectory); + + /** Clears the value of gcsOutputDirectory field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGcsOutputDirectory() { + return gcsOutputDirectory(Optional.empty()); + } + + /** + * Setter for bigqueryOutputTable. + * + *

    bigqueryOutputTable: The name of the BigQuery table created, in `predictions_` + * format, into which the prediction output is written. + */ + @JsonProperty("bigqueryOutputTable") + public abstract Builder bigqueryOutputTable(String bigqueryOutputTable); + + @ExcludeFromGeneratedCoverageReport + abstract Builder bigqueryOutputTable(Optional bigqueryOutputTable); + + /** Clears the value of bigqueryOutputTable field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBigqueryOutputTable() { + return bigqueryOutputTable(Optional.empty()); + } + + public abstract BatchJobOutputInfo build(); + } + + /** Deserializes a JSON string to a BatchJobOutputInfo object. */ + @ExcludeFromGeneratedCoverageReport + public static BatchJobOutputInfo fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, BatchJobOutputInfo.class); + } +} diff --git a/src/main/java/com/google/genai/types/BatchJobSource.java b/src/main/java/com/google/genai/types/BatchJobSource.java new file mode 100644 index 00000000000..cfcb82c41cf --- /dev/null +++ b/src/main/java/com/google/genai/types/BatchJobSource.java @@ -0,0 +1,234 @@ +/* + * 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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** Config for `src` parameter. */ +@AutoValue +@JsonDeserialize(builder = BatchJobSource.Builder.class) +public abstract class BatchJobSource extends JsonSerializable { + /** Storage format of the input files. Must be one of: 'jsonl', 'bigquery', 'vertex-dataset'. */ + @JsonProperty("format") + public abstract Optional format(); + + /** The Google Cloud Storage URIs to input files. */ + @JsonProperty("gcsUri") + public abstract Optional> gcsUri(); + + /** The BigQuery URI to input table. */ + @JsonProperty("bigqueryUri") + public abstract Optional bigqueryUri(); + + /** 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(); + + /** + * This field is experimental and may change in future versions. The Vertex AI dataset resource + * name to use as input. Must be of type multimodal. + */ + @JsonProperty("vertexDatasetName") + public abstract Optional vertexDatasetName(); + + /** Instantiates a builder for BatchJobSource. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_BatchJobSource.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for BatchJobSource. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `BatchJobSource.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_BatchJobSource.Builder(); + } + + /** + * Setter for format. + * + *

    format: Storage format of the input files. Must be one of: 'jsonl', 'bigquery', + * 'vertex-dataset'. + */ + @JsonProperty("format") + public abstract Builder format(String format); + + @ExcludeFromGeneratedCoverageReport + abstract Builder format(Optional format); + + /** Clears the value of format field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFormat() { + return format(Optional.empty()); + } + + /** + * Setter for gcsUri. + * + *

    gcsUri: The Google Cloud Storage URIs to input files. + */ + @JsonProperty("gcsUri") + public abstract Builder gcsUri(List gcsUri); + + /** + * Setter for gcsUri. + * + *

    gcsUri: The Google Cloud Storage URIs to input files. + */ + @CanIgnoreReturnValue + public Builder gcsUri(String... gcsUri) { + return gcsUri(Arrays.asList(gcsUri)); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder gcsUri(Optional> gcsUri); + + /** Clears the value of gcsUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGcsUri() { + return gcsUri(Optional.empty()); + } + + /** + * Setter for bigqueryUri. + * + *

    bigqueryUri: The BigQuery URI to input table. + */ + @JsonProperty("bigqueryUri") + public abstract Builder bigqueryUri(String bigqueryUri); + + @ExcludeFromGeneratedCoverageReport + abstract Builder bigqueryUri(Optional bigqueryUri); + + /** Clears the value of bigqueryUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBigqueryUri() { + return bigqueryUri(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder fileName(Optional fileName); + + /** Clears the value of fileName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFileName() { + return fileName(Optional.empty()); + } + + /** + * Setter for inlinedRequests. + * + *

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

    inlinedRequests: The Gemini Developer API's inlined input data to run batch job. + */ + @CanIgnoreReturnValue + public Builder inlinedRequests(InlinedRequest... inlinedRequests) { + return inlinedRequests(Arrays.asList(inlinedRequests)); + } + + /** + * Setter for inlinedRequests builder. + * + *

    inlinedRequests: The Gemini Developer API's inlined input data to run batch job. + */ + @CanIgnoreReturnValue + public Builder inlinedRequests(InlinedRequest.Builder... inlinedRequestsBuilders) { + return inlinedRequests( + Arrays.asList(inlinedRequestsBuilders).stream() + .map(InlinedRequest.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder inlinedRequests(Optional> inlinedRequests); + + /** Clears the value of inlinedRequests field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearInlinedRequests() { + return inlinedRequests(Optional.empty()); + } + + /** + * Setter for vertexDatasetName. + * + *

    vertexDatasetName: This field is experimental and may change in future versions. The + * Vertex AI dataset resource name to use as input. Must be of type multimodal. + */ + @JsonProperty("vertexDatasetName") + public abstract Builder vertexDatasetName(String vertexDatasetName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder vertexDatasetName(Optional vertexDatasetName); + + /** Clears the value of vertexDatasetName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearVertexDatasetName() { + return vertexDatasetName(Optional.empty()); + } + + public abstract BatchJobSource build(); + } + + /** 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..afce247558a 100644 --- a/src/main/java/com/google/genai/types/Behavior.java +++ b/src/main/java/com/google/genai/types/Behavior.java @@ -23,12 +23,16 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Defines the function behavior. Defaults to `BLOCKING`. */ +/** + * Specifies the function Behavior. Currently only non-blocking functions are supported. If not + * specified, the system keeps the current function call behavior. This field is currently only + * supported by the BidiGenerateContent method. + */ public class Behavior { /** Enum representing the known values for Behavior. */ public enum Known { - /** This value is unused. */ + /** This value is unspecified. */ UNSPECIFIED, /** @@ -69,12 +73,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 +107,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.behaviorEnum != Known.BEHAVIOR_UNSPECIFIED) { @@ -110,6 +117,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.behaviorEnum; } diff --git a/src/main/java/com/google/genai/types/BigQuerySource.java b/src/main/java/com/google/genai/types/BigQuerySource.java new file mode 100644 index 00000000000..06eb95f7702 --- /dev/null +++ b/src/main/java/com/google/genai/types/BigQuerySource.java @@ -0,0 +1,85 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 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; + +/** The BigQuery location for the input content. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = BigQuerySource.Builder.class) +public abstract class BigQuerySource extends JsonSerializable { + /** + * Required. BigQuery URI to a table, up to 2000 characters long. Accepted forms: * BigQuery path. + * For example: `bq://projectId.bqDatasetId.bqTableId`. + */ + @JsonProperty("inputUri") + public abstract Optional inputUri(); + + /** Instantiates a builder for BigQuerySource. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_BigQuerySource.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for BigQuerySource. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `BigQuerySource.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_BigQuerySource.Builder(); + } + + /** + * Setter for inputUri. + * + *

    inputUri: Required. BigQuery URI to a table, up to 2000 characters long. Accepted forms: * + * BigQuery path. For example: `bq://projectId.bqDatasetId.bqTableId`. + */ + @JsonProperty("inputUri") + public abstract Builder inputUri(String inputUri); + + @ExcludeFromGeneratedCoverageReport + abstract Builder inputUri(Optional inputUri); + + /** Clears the value of inputUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearInputUri() { + return inputUri(Optional.empty()); + } + + public abstract BigQuerySource build(); + } + + /** Deserializes a JSON string to a BigQuerySource object. */ + @ExcludeFromGeneratedCoverageReport + public static BigQuerySource fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, BigQuerySource.class); + } +} diff --git a/src/main/java/com/google/genai/types/BleuMetricValue.java b/src/main/java/com/google/genai/types/BleuMetricValue.java new file mode 100644 index 00000000000..695092bb30b --- /dev/null +++ b/src/main/java/com/google/genai/types/BleuMetricValue.java @@ -0,0 +1,81 @@ +/* + * 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; + +/** Bleu metric value for an instance. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = BleuMetricValue.Builder.class) +public abstract class BleuMetricValue extends JsonSerializable { + /** Output only. Bleu score. */ + @JsonProperty("score") + public abstract Optional score(); + + /** Instantiates a builder for BleuMetricValue. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_BleuMetricValue.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for BleuMetricValue. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `BleuMetricValue.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_BleuMetricValue.Builder(); + } + + /** + * Setter for score. + * + *

    score: Output only. Bleu score. + */ + @JsonProperty("score") + public abstract Builder score(Float score); + + @ExcludeFromGeneratedCoverageReport + abstract Builder score(Optional score); + + /** Clears the value of score field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearScore() { + return score(Optional.empty()); + } + + public abstract BleuMetricValue build(); + } + + /** Deserializes a JSON string to a BleuMetricValue object. */ + @ExcludeFromGeneratedCoverageReport + public static BleuMetricValue fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, BleuMetricValue.class); + } +} diff --git a/src/main/java/com/google/genai/types/BleuSpec.java b/src/main/java/com/google/genai/types/BleuSpec.java new file mode 100644 index 00000000000..bed20ecec20 --- /dev/null +++ b/src/main/java/com/google/genai/types/BleuSpec.java @@ -0,0 +1,81 @@ +/* + * 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; + +/** Spec for bleu metric. */ +@AutoValue +@JsonDeserialize(builder = BleuSpec.Builder.class) +public abstract class BleuSpec extends JsonSerializable { + /** Optional. Whether to use_effective_order to compute bleu score. */ + @JsonProperty("useEffectiveOrder") + public abstract Optional useEffectiveOrder(); + + /** Instantiates a builder for BleuSpec. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_BleuSpec.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for BleuSpec. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `BleuSpec.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_BleuSpec.Builder(); + } + + /** + * Setter for useEffectiveOrder. + * + *

    useEffectiveOrder: Optional. Whether to use_effective_order to compute bleu score. + */ + @JsonProperty("useEffectiveOrder") + public abstract Builder useEffectiveOrder(boolean useEffectiveOrder); + + @ExcludeFromGeneratedCoverageReport + abstract Builder useEffectiveOrder(Optional useEffectiveOrder); + + /** Clears the value of useEffectiveOrder field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUseEffectiveOrder() { + return useEffectiveOrder(Optional.empty()); + } + + public abstract BleuSpec build(); + } + + /** Deserializes a JSON string to a BleuSpec object. */ + @ExcludeFromGeneratedCoverageReport + public static BleuSpec fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, BleuSpec.class); + } +} diff --git a/src/main/java/com/google/genai/types/Blob.java b/src/main/java/com/google/genai/types/Blob.java index 923319396c5..c8fbbd16aa2 100644 --- a/src/main/java/com/google/genai/types/Blob.java +++ b/src/main/java/com/google/genai/types/Blob.java @@ -22,29 +22,36 @@ 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; -/** Content blob. */ +/** + * A content blob. A Blob contains data of a specific media type. It is used to represent images, + * audio, and video. + */ @AutoValue @JsonDeserialize(builder = Blob.Builder.class) public abstract class Blob extends JsonSerializable { + /** Required. The raw bytes of the data. */ + @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. + * Optional. The 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 used in the + * Gemini 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(); } @@ -62,21 +69,43 @@ private static Builder create() { } /** - * Setter for displayName. + * Setter for data. * - *

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

    data: Required. The raw bytes of the data. */ - @JsonProperty("displayName") - public abstract Builder displayName(String displayName); + @JsonProperty("data") + public abstract Builder data(byte[] data); + + @ExcludeFromGeneratedCoverageReport + abstract Builder data(Optional data); + + /** Clears the value of data field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearData() { + return data(Optional.empty()); + } /** - * Setter for data. + * Setter for displayName. * - *

    data: Required. Raw bytes. + *

    displayName: Optional. The 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 used in the Gemini calls only when server-side tools (`code_execution`, + * `google_search`, and `url_context`) are enabled. This field is not supported in Gemini API. */ - @JsonProperty("data") - public abstract Builder data(byte[] data); + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } /** * Setter for mimeType. @@ -86,10 +115,21 @@ private static Builder create() { @JsonProperty("mimeType") public abstract Builder mimeType(String mimeType); + @ExcludeFromGeneratedCoverageReport + abstract Builder mimeType(Optional mimeType); + + /** Clears the value of mimeType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMimeType() { + return mimeType(Optional.empty()); + } + public abstract Blob build(); } /** 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 790f3633cbc..399ff88b7a2 100644 --- a/src/main/java/com/google/genai/types/BlockedReason.java +++ b/src/main/java/com/google/genai/types/BlockedReason.java @@ -23,25 +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. */ - PROHIBITED_CONTENT + /** The prompt was blocked because it contains prohibited content. */ + PROHIBITED_CONTENT, + + /** 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; @@ -66,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) { @@ -98,6 +115,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.blockedReasonEnum != Known.BLOCKED_REASON_UNSPECIFIED) { @@ -107,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..09090b8a5be 100644 --- a/src/main/java/com/google/genai/types/CachedContent.java +++ b/src/main/java/com/google/genai/types/CachedContent.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.time.Instant; import java.util.Optional; @@ -59,6 +60,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(); } @@ -83,6 +85,16 @@ private static Builder create() { @JsonProperty("name") public abstract Builder name(String name); + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + /** * Setter for displayName. * @@ -91,6 +103,16 @@ private static Builder create() { @JsonProperty("displayName") public abstract Builder displayName(String displayName); + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + /** * Setter for model. * @@ -99,6 +121,16 @@ private static Builder create() { @JsonProperty("model") public abstract Builder model(String model); + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + /** * Setter for createTime. * @@ -107,6 +139,16 @@ private static Builder create() { @JsonProperty("createTime") public abstract Builder createTime(Instant createTime); + @ExcludeFromGeneratedCoverageReport + abstract Builder createTime(Optional createTime); + + /** Clears the value of createTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCreateTime() { + return createTime(Optional.empty()); + } + /** * Setter for updateTime. * @@ -115,6 +157,16 @@ private static Builder create() { @JsonProperty("updateTime") public abstract Builder updateTime(Instant updateTime); + @ExcludeFromGeneratedCoverageReport + abstract Builder updateTime(Optional updateTime); + + /** Clears the value of updateTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUpdateTime() { + return updateTime(Optional.empty()); + } + /** * Setter for expireTime. * @@ -123,6 +175,16 @@ private static Builder create() { @JsonProperty("expireTime") public abstract Builder expireTime(Instant expireTime); + @ExcludeFromGeneratedCoverageReport + abstract Builder expireTime(Optional expireTime); + + /** Clears the value of expireTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearExpireTime() { + return expireTime(Optional.empty()); + } + /** * Setter for usageMetadata. * @@ -136,14 +198,26 @@ private static Builder create() { * *

    usageMetadata: Metadata on the usage of the cached content. */ + @CanIgnoreReturnValue public Builder usageMetadata(CachedContentUsageMetadata.Builder usageMetadataBuilder) { return usageMetadata(usageMetadataBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder usageMetadata(Optional usageMetadata); + + /** Clears the value of usageMetadata field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUsageMetadata() { + return usageMetadata(Optional.empty()); + } + public abstract CachedContent build(); } /** 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..2c762cc5bd2 100644 --- a/src/main/java/com/google/genai/types/CachedContentUsageMetadata.java +++ b/src/main/java/com/google/genai/types/CachedContentUsageMetadata.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; @@ -29,15 +30,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 +46,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,27 +71,58 @@ 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder audioDurationSeconds(Optional audioDurationSeconds); + + /** Clears the value of audioDurationSeconds field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAudioDurationSeconds() { + return audioDurationSeconds(Optional.empty()); + } + /** * 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder imageCount(Optional imageCount); + + /** Clears the value of imageCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearImageCount() { + return imageCount(Optional.empty()); + } + /** * 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder textCount(Optional textCount); + + /** Clears the value of textCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTextCount() { + return textCount(Optional.empty()); + } + /** * Setter for totalTokenCount. * @@ -98,18 +131,40 @@ private static Builder create() { @JsonProperty("totalTokenCount") public abstract Builder totalTokenCount(Integer totalTokenCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder totalTokenCount(Optional totalTokenCount); + + /** Clears the value of totalTokenCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTotalTokenCount() { + return totalTokenCount(Optional.empty()); + } + /** * 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder videoDurationSeconds(Optional videoDurationSeconds); + + /** Clears the value of videoDurationSeconds field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearVideoDurationSeconds() { + return videoDurationSeconds(Optional.empty()); + } + public abstract CachedContentUsageMetadata build(); } /** 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 new file mode 100644 index 00000000000..efb10de2771 --- /dev/null +++ b/src/main/java/com/google/genai/types/CancelBatchJobConfig.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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Optional parameters. */ +@AutoValue +@JsonDeserialize(builder = CancelBatchJobConfig.Builder.class) +public abstract class CancelBatchJobConfig extends JsonSerializable { + /** Used to override HTTP request options. */ + @JsonProperty("httpOptions") + public abstract Optional httpOptions(); + + /** Instantiates a builder for CancelBatchJobConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CancelBatchJobConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CancelBatchJobConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CancelBatchJobConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CancelBatchJobConfig.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. + */ + @CanIgnoreReturnValue + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + + public abstract CancelBatchJobConfig build(); + } + + /** 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 new file mode 100644 index 00000000000..73dc9878d9b --- /dev/null +++ b/src/main/java/com/google/genai/types/CancelBatchJobParameters.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; + +/** Config for batches.cancel parameters. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = CancelBatchJobParameters.Builder.class) +public abstract class CancelBatchJobParameters extends JsonSerializable { + /** + * A fully-qualified BatchJob resource name or ID. Example: + * "projects/.../locations/.../batchPredictionJobs/456" or "456" when project and location are + * initialized in the client. + */ + @JsonProperty("name") + public abstract Optional name(); + + /** Optional parameters for the request. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for CancelBatchJobParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CancelBatchJobParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CancelBatchJobParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CancelBatchJobParameters.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CancelBatchJobParameters.Builder(); + } + + /** + * Setter for name. + * + *

    name: A fully-qualified BatchJob resource name or ID. Example: + * "projects/.../locations/.../batchPredictionJobs/456" or "456" when project and location are + * initialized in the client. + */ + @JsonProperty("name") + public abstract Builder name(String name); + + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + + /** + * Setter for config. + * + *

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

    config: Optional parameters for the request. + */ + @CanIgnoreReturnValue + public Builder config(CancelBatchJobConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + public abstract CancelBatchJobParameters build(); + } + + /** 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..7f31314ae68 --- /dev/null +++ b/src/main/java/com/google/genai/types/CancelTuningJobConfig.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.errorprone.annotations.CanIgnoreReturnValue; +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. + */ + @CanIgnoreReturnValue + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + + 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..c8ff1de99ad --- /dev/null +++ b/src/main/java/com/google/genai/types/CancelTuningJobParameters.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. + */ + +// 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; + +/** 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder config(CancelTuningJobConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + 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/CancelTuningJobResponse.java b/src/main/java/com/google/genai/types/CancelTuningJobResponse.java new file mode 100644 index 00000000000..e5bdd3713c3 --- /dev/null +++ b/src/main/java/com/google/genai/types/CancelTuningJobResponse.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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Empty response for tunings.cancel method. */ +@AutoValue +@JsonDeserialize(builder = CancelTuningJobResponse.Builder.class) +public abstract class CancelTuningJobResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + + /** Instantiates a builder for CancelTuningJobResponse. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CancelTuningJobResponse.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CancelTuningJobResponse. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CancelTuningJobResponse.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CancelTuningJobResponse.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. + */ + @CanIgnoreReturnValue + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + + public abstract CancelTuningJobResponse build(); + } + + /** Deserializes a JSON string to a CancelTuningJobResponse object. */ + @ExcludeFromGeneratedCoverageReport + public static CancelTuningJobResponse fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CancelTuningJobResponse.class); + } +} diff --git a/src/main/java/com/google/genai/types/Candidate.java b/src/main/java/com/google/genai/types/Candidate.java index 362ce25d9e5..814e4054708 100644 --- a/src/main/java/com/google/genai/types/Candidate.java +++ b/src/main/java/com/google/genai/types/Candidate.java @@ -57,34 +57,52 @@ 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. Metadata returned when grounding is enabled. It contains the sources used to + * ground the generated content. + */ + @JsonProperty("groundingMetadata") + public abstract Optional groundingMetadata(); - /** Output only. Average log probability score of the candidate. */ + /** + * Output only. The average log probability of the tokens in this candidate. This is a + * length-normalized score that can be used to compare the quality of candidates of different + * lengths. A higher average log probability suggests a more confident and coherent response. + */ @JsonProperty("avgLogprobs") public abstract Optional avgLogprobs(); - /** Output only. Metadata specifies sources used to ground generated content. */ - @JsonProperty("groundingMetadata") - public abstract Optional groundingMetadata(); - - /** Output only. Index of the candidate. */ + /** + * Output only. The 0-based index of this candidate in the list of generated responses. This is + * useful for distinguishing between multiple candidates when `candidate_count` > 1. + */ @JsonProperty("index") public abstract Optional index(); - /** Output only. Log-likelihood scores for the response tokens and top tokens */ + /** + * Output only. The detailed log probability information for the tokens in this candidate. This is + * useful for debugging, understanding model uncertainty, and identifying potential + * "hallucinations". + */ @JsonProperty("logprobsResult") public abstract Optional logprobsResult(); /** - * Output only. List of ratings for the safety of a response candidate. There is at most one + * Output only. A list of ratings for the safety of a response candidate. There is at most one * rating per category. */ @JsonProperty("safetyRatings") public abstract Optional> safetyRatings(); + /** + * Output only. Metadata returned when the model uses the `url_context` tool to get information + * from a user-provided URL. + */ + @JsonProperty("urlContextMetadata") + public abstract Optional urlContextMetadata(); + /** Instantiates a builder for Candidate. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Candidate.Builder(); } @@ -114,10 +132,21 @@ private static Builder create() { * *

    content: Contains the multi-part content of the response. */ + @CanIgnoreReturnValue public Builder content(Content.Builder contentBuilder) { return content(contentBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder content(Optional content); + + /** Clears the value of content field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearContent() { + return content(Optional.empty()); + } + /** * Setter for citationMetadata. * @@ -131,10 +160,21 @@ public Builder content(Content.Builder contentBuilder) { * *

    citationMetadata: Source attribution of the generated content. */ + @CanIgnoreReturnValue public Builder citationMetadata(CitationMetadata.Builder citationMetadataBuilder) { return citationMetadata(citationMetadataBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder citationMetadata(Optional citationMetadata); + + /** Clears the value of citationMetadata field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCitationMetadata() { + return citationMetadata(Optional.empty()); + } + /** * Setter for finishMessage. * @@ -143,6 +183,16 @@ public Builder citationMetadata(CitationMetadata.Builder citationMetadataBuilder @JsonProperty("finishMessage") public abstract Builder finishMessage(String finishMessage); + @ExcludeFromGeneratedCoverageReport + abstract Builder finishMessage(Optional finishMessage); + + /** Clears the value of finishMessage field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFinishMessage() { + return finishMessage(Optional.empty()); + } + /** * Setter for tokenCount. * @@ -151,6 +201,16 @@ public Builder citationMetadata(CitationMetadata.Builder citationMetadataBuilder @JsonProperty("tokenCount") public abstract Builder tokenCount(Integer tokenCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder tokenCount(Optional tokenCount); + + /** Clears the value of tokenCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTokenCount() { + return tokenCount(Optional.empty()); + } + /** * Setter for finishReason. * @@ -160,46 +220,43 @@ public Builder citationMetadata(CitationMetadata.Builder citationMetadataBuilder @JsonProperty("finishReason") public abstract Builder finishReason(FinishReason finishReason); - @CanIgnoreReturnValue - public Builder finishReason(FinishReason.Known knownType) { - return finishReason(new FinishReason(knownType)); - } + @ExcludeFromGeneratedCoverageReport + abstract Builder finishReason(Optional finishReason); + /** Clears the value of finishReason field. */ + @ExcludeFromGeneratedCoverageReport @CanIgnoreReturnValue - public Builder finishReason(String finishReason) { - return finishReason(new FinishReason(finishReason)); + public Builder clearFinishReason() { + return finishReason(Optional.empty()); } - /** - * Setter for urlContextMetadata. - * - *

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

    urlContextMetadata: Metadata related to url context retrieval tool. + *

    finishReason: The reason why the model stopped generating tokens. If empty, the model has + * not stopped generating the tokens. */ - public Builder urlContextMetadata(UrlContextMetadata.Builder urlContextMetadataBuilder) { - return urlContextMetadata(urlContextMetadataBuilder.build()); + @CanIgnoreReturnValue + public Builder finishReason(FinishReason.Known knownType) { + return finishReason(new FinishReason(knownType)); } /** - * Setter for avgLogprobs. + * Setter for finishReason given a string. * - *

    avgLogprobs: Output only. Average log probability score of the candidate. + *

    finishReason: The reason why the model stopped generating tokens. If empty, the model has + * not stopped generating the tokens. */ - @JsonProperty("avgLogprobs") - public abstract Builder avgLogprobs(Double avgLogprobs); + @CanIgnoreReturnValue + public Builder finishReason(String finishReason) { + return finishReason(new FinishReason(finishReason)); + } /** * Setter for groundingMetadata. * - *

    groundingMetadata: Output only. Metadata specifies sources used to ground generated - * content. + *

    groundingMetadata: Output only. Metadata returned when grounding is enabled. It contains + * the sources used to ground the generated content. */ @JsonProperty("groundingMetadata") public abstract Builder groundingMetadata(GroundingMetadata groundingMetadata); @@ -207,25 +264,71 @@ public Builder urlContextMetadata(UrlContextMetadata.Builder urlContextMetadataB /** * Setter for groundingMetadata builder. * - *

    groundingMetadata: Output only. Metadata specifies sources used to ground generated - * content. + *

    groundingMetadata: Output only. Metadata returned when grounding is enabled. It contains + * the sources used to ground the generated content. */ + @CanIgnoreReturnValue public Builder groundingMetadata(GroundingMetadata.Builder groundingMetadataBuilder) { return groundingMetadata(groundingMetadataBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder groundingMetadata(Optional groundingMetadata); + + /** Clears the value of groundingMetadata field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGroundingMetadata() { + return groundingMetadata(Optional.empty()); + } + + /** + * Setter for avgLogprobs. + * + *

    avgLogprobs: Output only. The average log probability of the tokens in this candidate. + * This is a length-normalized score that can be used to compare the quality of candidates of + * different lengths. A higher average log probability suggests a more confident and coherent + * response. + */ + @JsonProperty("avgLogprobs") + public abstract Builder avgLogprobs(Double avgLogprobs); + + @ExcludeFromGeneratedCoverageReport + abstract Builder avgLogprobs(Optional avgLogprobs); + + /** Clears the value of avgLogprobs field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAvgLogprobs() { + return avgLogprobs(Optional.empty()); + } + /** * Setter for index. * - *

    index: Output only. Index of the candidate. + *

    index: Output only. The 0-based index of this candidate in the list of generated + * responses. This is useful for distinguishing between multiple candidates when + * `candidate_count` > 1. */ @JsonProperty("index") public abstract Builder index(Integer index); + @ExcludeFromGeneratedCoverageReport + abstract Builder index(Optional index); + + /** Clears the value of index field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearIndex() { + return index(Optional.empty()); + } + /** * Setter for logprobsResult. * - *

    logprobsResult: Output only. Log-likelihood scores for the response tokens and top tokens + *

    logprobsResult: Output only. The detailed log probability information for the tokens in + * this candidate. This is useful for debugging, understanding model uncertainty, and + * identifying potential "hallucinations". */ @JsonProperty("logprobsResult") public abstract Builder logprobsResult(LogprobsResult logprobsResult); @@ -233,17 +336,30 @@ public Builder groundingMetadata(GroundingMetadata.Builder groundingMetadataBuil /** * Setter for logprobsResult builder. * - *

    logprobsResult: Output only. Log-likelihood scores for the response tokens and top tokens + *

    logprobsResult: Output only. The detailed log probability information for the tokens in + * this candidate. This is useful for debugging, understanding model uncertainty, and + * identifying potential "hallucinations". */ + @CanIgnoreReturnValue public Builder logprobsResult(LogprobsResult.Builder logprobsResultBuilder) { return logprobsResult(logprobsResultBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder logprobsResult(Optional logprobsResult); + + /** Clears the value of logprobsResult field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLogprobsResult() { + return logprobsResult(Optional.empty()); + } + /** * Setter for safetyRatings. * - *

    safetyRatings: Output only. List of ratings for the safety of a response candidate. There - * is at most one rating per category. + *

    safetyRatings: Output only. A list of ratings for the safety of a response candidate. + * There is at most one rating per category. */ @JsonProperty("safetyRatings") public abstract Builder safetyRatings(List safetyRatings); @@ -251,9 +367,10 @@ public Builder logprobsResult(LogprobsResult.Builder logprobsResultBuilder) { /** * Setter for safetyRatings. * - *

    safetyRatings: Output only. List of ratings for the safety of a response candidate. There - * is at most one rating per category. + *

    safetyRatings: Output only. A list of ratings for the safety of a response candidate. + * There is at most one rating per category. */ + @CanIgnoreReturnValue public Builder safetyRatings(SafetyRating... safetyRatings) { return safetyRatings(Arrays.asList(safetyRatings)); } @@ -261,9 +378,10 @@ public Builder safetyRatings(SafetyRating... safetyRatings) { /** * Setter for safetyRatings builder. * - *

    safetyRatings: Output only. List of ratings for the safety of a response candidate. There - * is at most one rating per category. + *

    safetyRatings: Output only. A list of ratings for the safety of a response candidate. + * There is at most one rating per category. */ + @CanIgnoreReturnValue public Builder safetyRatings(SafetyRating.Builder... safetyRatingsBuilders) { return safetyRatings( Arrays.asList(safetyRatingsBuilders).stream() @@ -271,10 +389,51 @@ public Builder safetyRatings(SafetyRating.Builder... safetyRatingsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder safetyRatings(Optional> safetyRatings); + + /** Clears the value of safetyRatings field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSafetyRatings() { + return safetyRatings(Optional.empty()); + } + + /** + * Setter for urlContextMetadata. + * + *

    urlContextMetadata: Output only. Metadata returned when the model uses the `url_context` + * tool to get information from a user-provided URL. + */ + @JsonProperty("urlContextMetadata") + public abstract Builder urlContextMetadata(UrlContextMetadata urlContextMetadata); + + /** + * Setter for urlContextMetadata builder. + * + *

    urlContextMetadata: Output only. Metadata returned when the model uses the `url_context` + * tool to get information from a user-provided URL. + */ + @CanIgnoreReturnValue + public Builder urlContextMetadata(UrlContextMetadata.Builder urlContextMetadataBuilder) { + return urlContextMetadata(urlContextMetadataBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder urlContextMetadata(Optional urlContextMetadata); + + /** Clears the value of urlContextMetadata field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUrlContextMetadata() { + return urlContextMetadata(Optional.empty()); + } + 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..24ae1ddbcd9 100644 --- a/src/main/java/com/google/genai/types/Checkpoint.java +++ b/src/main/java/com/google/genai/types/Checkpoint.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; @@ -42,6 +43,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(); } @@ -66,6 +68,16 @@ private static Builder create() { @JsonProperty("checkpointId") public abstract Builder checkpointId(String checkpointId); + @ExcludeFromGeneratedCoverageReport + abstract Builder checkpointId(Optional checkpointId); + + /** Clears the value of checkpointId field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCheckpointId() { + return checkpointId(Optional.empty()); + } + /** * Setter for epoch. * @@ -74,6 +86,16 @@ private static Builder create() { @JsonProperty("epoch") public abstract Builder epoch(Long epoch); + @ExcludeFromGeneratedCoverageReport + abstract Builder epoch(Optional epoch); + + /** Clears the value of epoch field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEpoch() { + return epoch(Optional.empty()); + } + /** * Setter for step. * @@ -82,10 +104,21 @@ private static Builder create() { @JsonProperty("step") public abstract Builder step(Long step); + @ExcludeFromGeneratedCoverageReport + abstract Builder step(Optional step); + + /** Clears the value of step field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearStep() { + return step(Optional.empty()); + } + public abstract Checkpoint build(); } /** 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/ChunkingConfig.java b/src/main/java/com/google/genai/types/ChunkingConfig.java new file mode 100644 index 00000000000..ea20267ae05 --- /dev/null +++ b/src/main/java/com/google/genai/types/ChunkingConfig.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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Config for telling the service how to chunk the file. */ +@AutoValue +@JsonDeserialize(builder = ChunkingConfig.Builder.class) +public abstract class ChunkingConfig extends JsonSerializable { + /** White space chunking configuration. */ + @JsonProperty("whiteSpaceConfig") + public abstract Optional whiteSpaceConfig(); + + /** Instantiates a builder for ChunkingConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ChunkingConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ChunkingConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ChunkingConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ChunkingConfig.Builder(); + } + + /** + * Setter for whiteSpaceConfig. + * + *

    whiteSpaceConfig: White space chunking configuration. + */ + @JsonProperty("whiteSpaceConfig") + public abstract Builder whiteSpaceConfig(WhiteSpaceConfig whiteSpaceConfig); + + /** + * Setter for whiteSpaceConfig builder. + * + *

    whiteSpaceConfig: White space chunking configuration. + */ + @CanIgnoreReturnValue + public Builder whiteSpaceConfig(WhiteSpaceConfig.Builder whiteSpaceConfigBuilder) { + return whiteSpaceConfig(whiteSpaceConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder whiteSpaceConfig(Optional whiteSpaceConfig); + + /** Clears the value of whiteSpaceConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearWhiteSpaceConfig() { + return whiteSpaceConfig(Optional.empty()); + } + + public abstract ChunkingConfig build(); + } + + /** Deserializes a JSON string to a ChunkingConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static ChunkingConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, ChunkingConfig.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..38175b0b581 100644 --- a/src/main/java/com/google/genai/types/Citation.java +++ b/src/main/java/com/google/genai/types/Citation.java @@ -22,38 +22,40 @@ 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; -/** Source attributions for content. */ +/** A citation for a piece of generatedcontent. This data type is not supported in Gemini API. */ @AutoValue @JsonDeserialize(builder = Citation.Builder.class) public abstract class Citation extends JsonSerializable { - /** Output only. End index into the content. */ + /** Output only. The end index of the citation in the content. */ @JsonProperty("endIndex") public abstract Optional endIndex(); - /** Output only. License of the attribution. */ + /** Output only. The license of the source of the citation. */ @JsonProperty("license") public abstract Optional license(); - /** Output only. Publication date of the attribution. */ + /** Output only. The publication date of the source of the citation. */ @JsonProperty("publicationDate") public abstract Optional publicationDate(); - /** Output only. Start index into the content. */ + /** Output only. The start index of the citation in the content. */ @JsonProperty("startIndex") public abstract Optional startIndex(); - /** Output only. Title of the attribution. */ + /** Output only. The title of the source of the citation. */ @JsonProperty("title") public abstract Optional title(); - /** Output only. Url reference of the attribution. */ + /** Output only. The URI of the source of the citation. */ @JsonProperty("uri") public abstract Optional uri(); /** Instantiates a builder for Citation. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Citation.Builder(); } @@ -73,23 +75,43 @@ private static Builder create() { /** * Setter for endIndex. * - *

    endIndex: Output only. End index into the content. + *

    endIndex: Output only. The end index of the citation in the content. */ @JsonProperty("endIndex") public abstract Builder endIndex(Integer endIndex); + @ExcludeFromGeneratedCoverageReport + abstract Builder endIndex(Optional endIndex); + + /** Clears the value of endIndex field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEndIndex() { + return endIndex(Optional.empty()); + } + /** * Setter for license. * - *

    license: Output only. License of the attribution. + *

    license: Output only. The license of the source of the citation. */ @JsonProperty("license") public abstract Builder license(String license); + @ExcludeFromGeneratedCoverageReport + abstract Builder license(Optional license); + + /** Clears the value of license field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLicense() { + return license(Optional.empty()); + } + /** * Setter for publicationDate. * - *

    publicationDate: Output only. Publication date of the attribution. + *

    publicationDate: Output only. The publication date of the source of the citation. */ @JsonProperty("publicationDate") public abstract Builder publicationDate(GoogleTypeDate publicationDate); @@ -97,40 +119,82 @@ private static Builder create() { /** * Setter for publicationDate builder. * - *

    publicationDate: Output only. Publication date of the attribution. + *

    publicationDate: Output only. The publication date of the source of the citation. */ + @CanIgnoreReturnValue public Builder publicationDate(GoogleTypeDate.Builder publicationDateBuilder) { return publicationDate(publicationDateBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder publicationDate(Optional publicationDate); + + /** Clears the value of publicationDate field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPublicationDate() { + return publicationDate(Optional.empty()); + } + /** * Setter for startIndex. * - *

    startIndex: Output only. Start index into the content. + *

    startIndex: Output only. The start index of the citation in the content. */ @JsonProperty("startIndex") public abstract Builder startIndex(Integer startIndex); + @ExcludeFromGeneratedCoverageReport + abstract Builder startIndex(Optional startIndex); + + /** Clears the value of startIndex field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearStartIndex() { + return startIndex(Optional.empty()); + } + /** * Setter for title. * - *

    title: Output only. Title of the attribution. + *

    title: Output only. The title of the source of the citation. */ @JsonProperty("title") public abstract Builder title(String title); + @ExcludeFromGeneratedCoverageReport + abstract Builder title(Optional title); + + /** Clears the value of title field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTitle() { + return title(Optional.empty()); + } + /** * Setter for uri. * - *

    uri: Output only. Url reference of the attribution. + *

    uri: Output only. The URI of the source of the citation. */ @JsonProperty("uri") public abstract Builder uri(String uri); + @ExcludeFromGeneratedCoverageReport + abstract Builder uri(Optional uri); + + /** Clears the value of uri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUri() { + return uri(Optional.empty()); + } + public abstract Citation build(); } /** 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..18efb797ca1 100644 --- a/src/main/java/com/google/genai/types/CitationMetadata.java +++ b/src/main/java/com/google/genai/types/CitationMetadata.java @@ -24,6 +24,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.Arrays; import java.util.List; @@ -41,6 +42,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(); } @@ -72,6 +74,7 @@ private static Builder create() { *

    citations: Contains citation information when the model directly quotes, at length, from * another source. Can include traditional websites and code repositories. */ + @CanIgnoreReturnValue public Builder citations(Citation... citations) { return citations(Arrays.asList(citations)); } @@ -82,6 +85,7 @@ public Builder citations(Citation... citations) { *

    citations: Contains citation information when the model directly quotes, at length, from * another source. Can include traditional websites and code repositories. */ + @CanIgnoreReturnValue public Builder citations(Citation.Builder... citationsBuilders) { return citations( Arrays.asList(citationsBuilders).stream() @@ -89,10 +93,21 @@ public Builder citations(Citation.Builder... citationsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder citations(Optional> citations); + + /** Clears the value of citations field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCitations() { + return citations(Optional.empty()); + } + public abstract CitationMetadata build(); } /** 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 new file mode 100644 index 00000000000..f6827d7a83b --- /dev/null +++ b/src/main/java/com/google/genai/types/ClientOptions.java @@ -0,0 +1,135 @@ +/* + * 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; + +/** Client options to be used in the client instantiation. */ +@AutoValue +@JsonDeserialize(builder = ClientOptions.Builder.class) +public abstract class ClientOptions extends JsonSerializable { + /** The maximum number of connections allowed in the pool. */ + @JsonProperty("maxConnections") + public abstract Optional maxConnections(); + + /** The maximum number of connections allowed per host. */ + @JsonProperty("maxConnectionsPerHost") + public abstract Optional maxConnectionsPerHost(); + + /** Proxy configuration to be used in the client. */ + @JsonProperty("proxyOptions") + public abstract Optional proxyOptions(); + + /** Instantiates a builder for ClientOptions. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ClientOptions.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ClientOptions. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ClientOptions.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ClientOptions.Builder(); + } + + /** + * Setter for maxConnections. + * + *

    maxConnections: The maximum number of connections allowed in the pool. + */ + @JsonProperty("maxConnections") + public abstract Builder maxConnections(Integer maxConnections); + + @ExcludeFromGeneratedCoverageReport + abstract Builder maxConnections(Optional maxConnections); + + /** Clears the value of maxConnections field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMaxConnections() { + return maxConnections(Optional.empty()); + } + + /** + * Setter for maxConnectionsPerHost. + * + *

    maxConnectionsPerHost: The maximum number of connections allowed per host. + */ + @JsonProperty("maxConnectionsPerHost") + public abstract Builder maxConnectionsPerHost(Integer maxConnectionsPerHost); + + @ExcludeFromGeneratedCoverageReport + abstract Builder maxConnectionsPerHost(Optional maxConnectionsPerHost); + + /** Clears the value of maxConnectionsPerHost field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMaxConnectionsPerHost() { + return maxConnectionsPerHost(Optional.empty()); + } + + /** + * Setter for proxyOptions. + * + *

    proxyOptions: Proxy configuration to be used in the client. + */ + @JsonProperty("proxyOptions") + public abstract Builder proxyOptions(ProxyOptions proxyOptions); + + /** + * Setter for proxyOptions builder. + * + *

    proxyOptions: Proxy configuration to be used in the client. + */ + @CanIgnoreReturnValue + public Builder proxyOptions(ProxyOptions.Builder proxyOptionsBuilder) { + return proxyOptions(proxyOptionsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder proxyOptions(Optional proxyOptions); + + /** Clears the value of proxyOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearProxyOptions() { + return proxyOptions(Optional.empty()); + } + + public abstract ClientOptions build(); + } + + /** 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 53c5199571f..93c86706b1b 100644 --- a/src/main/java/com/google/genai/types/CodeExecutionResult.java +++ b/src/main/java/com/google/genai/types/CodeExecutionResult.java @@ -27,8 +27,9 @@ import java.util.Optional; /** - * Result of executing the [ExecutableCode]. Always follows a `part` containing the - * [ExecutableCode]. + * Result of executing the `ExecutableCode`. + * + *

    Generated only when the `CodeExecution` tool is used. */ @AutoValue @JsonDeserialize(builder = CodeExecutionResult.Builder.class) @@ -44,7 +45,15 @@ public abstract class CodeExecutionResult extends JsonSerializable { @JsonProperty("output") public abstract Optional output(); + /** + * The identifier of the `ExecutableCode` part this result is for. Only populated if the + * corresponding `ExecutableCode` has an id. + */ + @JsonProperty("id") + public abstract Optional id(); + /** Instantiates a builder for CodeExecutionResult. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CodeExecutionResult.Builder(); } @@ -69,29 +78,79 @@ private static Builder create() { @JsonProperty("outcome") public abstract Builder outcome(Outcome outcome); + @ExcludeFromGeneratedCoverageReport + abstract Builder outcome(Optional outcome); + + /** Clears the value of outcome field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutcome() { + return outcome(Optional.empty()); + } + + /** + * Setter for outcome given a known enum. + * + *

    outcome: Required. Outcome of the code execution. + */ @CanIgnoreReturnValue public Builder outcome(Outcome.Known knownType) { return outcome(new Outcome(knownType)); } + /** + * Setter for outcome given a string. + * + *

    outcome: Required. Outcome of the code execution. + */ @CanIgnoreReturnValue public Builder outcome(String outcome) { return outcome(new Outcome(outcome)); } + /** * Setter for output. * *

    output: Optional. Contains stdout when code execution is successful, stderr or other * description otherwise. */ - @JsonProperty("output") public abstract Builder output(String output); + @ExcludeFromGeneratedCoverageReport + abstract Builder output(Optional output); + + /** Clears the value of output field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutput() { + return output(Optional.empty()); + } + + /** + * Setter for id. + * + *

    id: The identifier of the `ExecutableCode` part this result is for. Only populated if the + * corresponding `ExecutableCode` has an id. + */ + @JsonProperty("id") + public abstract Builder id(String id); + + @ExcludeFromGeneratedCoverageReport + abstract Builder id(Optional id); + + /** Clears the value of id field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearId() { + return id(Optional.empty()); + } + public abstract CodeExecutionResult build(); } /** 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/CompletionStats.java b/src/main/java/com/google/genai/types/CompletionStats.java new file mode 100644 index 00000000000..e505496521c --- /dev/null +++ b/src/main/java/com/google/genai/types/CompletionStats.java @@ -0,0 +1,164 @@ +/* + * 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; + +/** + * Success and error statistics of processing multiple entities (for example, DataItems or + * structured data rows) in batch. This data type is not supported in Gemini API. + */ +@AutoValue +@JsonDeserialize(builder = CompletionStats.Builder.class) +public abstract class CompletionStats extends JsonSerializable { + /** Output only. The number of entities for which any error was encountered. */ + @JsonProperty("failedCount") + public abstract Optional failedCount(); + + /** + * Output only. In cases when enough errors are encountered a job, pipeline, or operation may be + * failed as a whole. Below is the number of entities for which the processing had not been + * finished (either in successful or failed state). Set to -1 if the number is unknown (for + * example, the operation failed before the total entity number could be collected). + */ + @JsonProperty("incompleteCount") + public abstract Optional incompleteCount(); + + /** Output only. The number of entities that had been processed successfully. */ + @JsonProperty("successfulCount") + public abstract Optional successfulCount(); + + /** + * Output only. The number of the successful forecast points that are generated by the forecasting + * model. This is ONLY used by the forecasting batch prediction. + */ + @JsonProperty("successfulForecastPointCount") + public abstract Optional successfulForecastPointCount(); + + /** Instantiates a builder for CompletionStats. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CompletionStats.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CompletionStats. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CompletionStats.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CompletionStats.Builder(); + } + + /** + * Setter for failedCount. + * + *

    failedCount: Output only. The number of entities for which any error was encountered. + */ + @JsonProperty("failedCount") + public abstract Builder failedCount(Long failedCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder failedCount(Optional failedCount); + + /** Clears the value of failedCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFailedCount() { + return failedCount(Optional.empty()); + } + + /** + * Setter for incompleteCount. + * + *

    incompleteCount: Output only. In cases when enough errors are encountered a job, pipeline, + * or operation may be failed as a whole. Below is the number of entities for which the + * processing had not been finished (either in successful or failed state). Set to -1 if the + * number is unknown (for example, the operation failed before the total entity number could be + * collected). + */ + @JsonProperty("incompleteCount") + public abstract Builder incompleteCount(Long incompleteCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder incompleteCount(Optional incompleteCount); + + /** Clears the value of incompleteCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearIncompleteCount() { + return incompleteCount(Optional.empty()); + } + + /** + * Setter for successfulCount. + * + *

    successfulCount: Output only. The number of entities that had been processed successfully. + */ + @JsonProperty("successfulCount") + public abstract Builder successfulCount(Long successfulCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder successfulCount(Optional successfulCount); + + /** Clears the value of successfulCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSuccessfulCount() { + return successfulCount(Optional.empty()); + } + + /** + * Setter for successfulForecastPointCount. + * + *

    successfulForecastPointCount: Output only. The number of the successful forecast points + * that are generated by the forecasting model. This is ONLY used by the forecasting batch + * prediction. + */ + @JsonProperty("successfulForecastPointCount") + public abstract Builder successfulForecastPointCount(Long successfulForecastPointCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder successfulForecastPointCount(Optional successfulForecastPointCount); + + /** Clears the value of successfulForecastPointCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSuccessfulForecastPointCount() { + return successfulForecastPointCount(Optional.empty()); + } + + public abstract CompletionStats build(); + } + + /** Deserializes a JSON string to a CompletionStats object. */ + @ExcludeFromGeneratedCoverageReport + public static CompletionStats fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CompletionStats.class); + } +} diff --git a/src/main/java/com/google/genai/types/ComputationBasedMetricSpec.java b/src/main/java/com/google/genai/types/ComputationBasedMetricSpec.java new file mode 100644 index 00000000000..9e45a672f20 --- /dev/null +++ b/src/main/java/com/google/genai/types/ComputationBasedMetricSpec.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 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; + +/** Specification for a computation based metric. */ +@AutoValue +@JsonDeserialize(builder = ComputationBasedMetricSpec.Builder.class) +public abstract class ComputationBasedMetricSpec extends JsonSerializable { + /** The type of the computation based metric. */ + @JsonProperty("type") + public abstract Optional type(); + + /** + * A map of parameters for the metric. ROUGE example: {"rouge_type": "rougeL", "split_summaries": + * True, "use_stemmer": True}. BLEU example: {"use_effective_order": True}. + */ + @JsonProperty("parameters") + public abstract Optional> parameters(); + + /** Instantiates a builder for ComputationBasedMetricSpec. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ComputationBasedMetricSpec.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ComputationBasedMetricSpec. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ComputationBasedMetricSpec.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ComputationBasedMetricSpec.Builder(); + } + + /** + * Setter for type. + * + *

    type: The type of the computation based metric. + */ + @JsonProperty("type") + public abstract Builder type(ComputationBasedMetricType type); + + @ExcludeFromGeneratedCoverageReport + abstract Builder type(Optional type); + + /** Clears the value of type field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearType() { + return type(Optional.empty()); + } + + /** + * Setter for type given a known enum. + * + *

    type: The type of the computation based metric. + */ + @CanIgnoreReturnValue + public Builder type(ComputationBasedMetricType.Known knownType) { + return type(new ComputationBasedMetricType(knownType)); + } + + /** + * Setter for type given a string. + * + *

    type: The type of the computation based metric. + */ + @CanIgnoreReturnValue + public Builder type(String type) { + return type(new ComputationBasedMetricType(type)); + } + + /** + * Setter for parameters. + * + *

    parameters: A map of parameters for the metric. ROUGE example: {"rouge_type": "rougeL", + * "split_summaries": True, "use_stemmer": True}. BLEU example: {"use_effective_order": True}. + */ + @JsonProperty("parameters") + public abstract Builder parameters(Map parameters); + + @ExcludeFromGeneratedCoverageReport + abstract Builder parameters(Optional> parameters); + + /** Clears the value of parameters field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearParameters() { + return parameters(Optional.empty()); + } + + public abstract ComputationBasedMetricSpec build(); + } + + /** Deserializes a JSON string to a ComputationBasedMetricSpec object. */ + @ExcludeFromGeneratedCoverageReport + public static ComputationBasedMetricSpec fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, ComputationBasedMetricSpec.class); + } +} diff --git a/src/main/java/com/google/genai/types/ComputationBasedMetricType.java b/src/main/java/com/google/genai/types/ComputationBasedMetricType.java new file mode 100644 index 00000000000..20fbabebd9e --- /dev/null +++ b/src/main/java/com/google/genai/types/ComputationBasedMetricType.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.JsonValue; +import com.google.common.base.Ascii; +import java.util.Objects; + +/** Represents the type of the computation based metric. */ +public class ComputationBasedMetricType { + + /** Enum representing the known values for ComputationBasedMetricType. */ + public enum Known { + /** Computation based metric type is unspecified. */ + COMPUTATION_BASED_METRIC_TYPE_UNSPECIFIED, + + /** Exact match metric. */ + EXACT_MATCH, + + /** BLEU metric. */ + BLEU, + + /** ROUGE metric. */ + ROUGE + } + + private Known computationBasedMetricTypeEnum; + private final String value; + + @JsonCreator + public ComputationBasedMetricType(String value) { + this.value = value; + for (Known computationBasedMetricTypeEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(computationBasedMetricTypeEnum.toString(), value)) { + this.computationBasedMetricTypeEnum = computationBasedMetricTypeEnum; + break; + } + } + if (this.computationBasedMetricTypeEnum == null) { + this.computationBasedMetricTypeEnum = Known.COMPUTATION_BASED_METRIC_TYPE_UNSPECIFIED; + } + } + + public ComputationBasedMetricType(Known knownValue) { + this.computationBasedMetricTypeEnum = 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 ComputationBasedMetricType)) { + return false; + } + + ComputationBasedMetricType other = (ComputationBasedMetricType) o; + + if (this.computationBasedMetricTypeEnum != Known.COMPUTATION_BASED_METRIC_TYPE_UNSPECIFIED + && other.computationBasedMetricTypeEnum + != Known.COMPUTATION_BASED_METRIC_TYPE_UNSPECIFIED) { + return this.computationBasedMetricTypeEnum == other.computationBasedMetricTypeEnum; + } else if (this.computationBasedMetricTypeEnum + == Known.COMPUTATION_BASED_METRIC_TYPE_UNSPECIFIED + && other.computationBasedMetricTypeEnum + == Known.COMPUTATION_BASED_METRIC_TYPE_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.computationBasedMetricTypeEnum != Known.COMPUTATION_BASED_METRIC_TYPE_UNSPECIFIED) { + return this.computationBasedMetricTypeEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.computationBasedMetricTypeEnum; + } +} diff --git a/src/main/java/com/google/genai/types/ComputeTokensConfig.java b/src/main/java/com/google/genai/types/ComputeTokensConfig.java index 6db60ccd1d9..3a4bee91d45 100644 --- a/src/main/java/com/google/genai/types/ComputeTokensConfig.java +++ b/src/main/java/com/google/genai/types/ComputeTokensConfig.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; @@ -34,6 +35,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(); } @@ -63,14 +65,26 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + public abstract ComputeTokensConfig build(); } /** 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..c8bf85d8a86 100644 --- a/src/main/java/com/google/genai/types/ComputeTokensParameters.java +++ b/src/main/java/com/google/genai/types/ComputeTokensParameters.java @@ -25,6 +25,7 @@ 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.Arrays; import java.util.List; @@ -51,6 +52,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(); } @@ -76,6 +78,16 @@ private static Builder create() { @JsonProperty("model") public abstract Builder model(String model); + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + /** * Setter for contents. * @@ -89,6 +101,7 @@ private static Builder create() { * *

    contents: Input content. */ + @CanIgnoreReturnValue public Builder contents(Content... contents) { return contents(Arrays.asList(contents)); } @@ -98,6 +111,7 @@ public Builder contents(Content... contents) { * *

    contents: Input content. */ + @CanIgnoreReturnValue public Builder contents(Content.Builder... contentsBuilders) { return contents( Arrays.asList(contentsBuilders).stream() @@ -105,6 +119,16 @@ public Builder contents(Content.Builder... contentsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder contents(Optional> contents); + + /** Clears the value of contents field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearContents() { + return contents(Optional.empty()); + } + /** * Setter for config. * @@ -118,14 +142,26 @@ public Builder contents(Content.Builder... contentsBuilders) { * *

    config: Optional parameters for the request. */ + @CanIgnoreReturnValue public Builder config(ComputeTokensConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract ComputeTokensParameters build(); } /** 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..7c4660bb43a 100644 --- a/src/main/java/com/google/genai/types/ComputeTokensResponse.java +++ b/src/main/java/com/google/genai/types/ComputeTokensResponse.java @@ -24,6 +24,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.Arrays; import java.util.List; @@ -33,6 +34,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 +47,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 +64,34 @@ 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. + */ + @CanIgnoreReturnValue + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + /** * Setter for tokensInfo. * @@ -75,6 +109,7 @@ private static Builder create() { * multiple instances with a prompt in each instance. We also need to return lists of tokens * info for the request with multiple instances. */ + @CanIgnoreReturnValue public Builder tokensInfo(TokensInfo... tokensInfo) { return tokensInfo(Arrays.asList(tokensInfo)); } @@ -86,6 +121,7 @@ public Builder tokensInfo(TokensInfo... tokensInfo) { * multiple instances with a prompt in each instance. We also need to return lists of tokens * info for the request with multiple instances. */ + @CanIgnoreReturnValue public Builder tokensInfo(TokensInfo.Builder... tokensInfoBuilders) { return tokensInfo( Arrays.asList(tokensInfoBuilders).stream() @@ -93,10 +129,21 @@ public Builder tokensInfo(TokensInfo.Builder... tokensInfoBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder tokensInfo(Optional> tokensInfo); + + /** Clears the value of tokensInfo field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTokensInfo() { + return tokensInfo(Optional.empty()); + } + public abstract ComputeTokensResponse build(); } /** 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..893e9647031 --- /dev/null +++ b/src/main/java/com/google/genai/types/ComputeTokensResult.java @@ -0,0 +1,108 @@ +/* + * 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.errorprone.annotations.CanIgnoreReturnValue; +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. + */ + @CanIgnoreReturnValue + public Builder tokensInfo(TokensInfo... tokensInfo) { + return tokensInfo(Arrays.asList(tokensInfo)); + } + + /** + * Setter for tokensInfo builder. + * + *

    tokensInfo: Lists of tokens info from the input. + */ + @CanIgnoreReturnValue + public Builder tokensInfo(TokensInfo.Builder... tokensInfoBuilders) { + return tokensInfo( + Arrays.asList(tokensInfoBuilders).stream() + .map(TokensInfo.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder tokensInfo(Optional> tokensInfo); + + /** Clears the value of tokensInfo field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTokensInfo() { + return tokensInfo(Optional.empty()); + } + + 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..48ecdba8548 --- /dev/null +++ b/src/main/java/com/google/genai/types/ComputerUse.java @@ -0,0 +1,147 @@ +/* + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder environment(Optional environment); + + /** Clears the value of environment field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEnvironment() { + return environment(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder excludedPredefinedFunctions(String... excludedPredefinedFunctions) { + return excludedPredefinedFunctions(Arrays.asList(excludedPredefinedFunctions)); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder excludedPredefinedFunctions( + Optional> excludedPredefinedFunctions); + + /** Clears the value of excludedPredefinedFunctions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearExcludedPredefinedFunctions() { + return excludedPredefinedFunctions(Optional.empty()); + } + + 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..3107d7a9e08 100644 --- a/src/main/java/com/google/genai/types/Content.java +++ b/src/main/java/com/google/genai/types/Content.java @@ -24,6 +24,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.ArrayList; import java.util.Arrays; @@ -43,14 +44,14 @@ public abstract class Content extends JsonSerializable { public abstract Optional> parts(); /** - * 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. + * Optional. The producer of the content. Must be either 'user' or 'model'. If not set, the + * service will default to 'user'. */ @JsonProperty("role") public abstract Optional role(); /** Instantiates a builder for Content. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_Content.Builder(); } @@ -82,6 +83,7 @@ private static Builder create() { *

    parts: List of parts that constitute a single message. Each part may have a different IANA * MIME type. */ + @CanIgnoreReturnValue public Builder parts(Part... parts) { return parts(Arrays.asList(parts)); } @@ -92,6 +94,7 @@ public Builder parts(Part... parts) { *

    parts: List of parts that constitute a single message. Each part may have a different IANA * MIME type. */ + @CanIgnoreReturnValue public Builder parts(Part.Builder... partsBuilders) { return parts( Arrays.asList(partsBuilders).stream() @@ -99,20 +102,40 @@ public Builder parts(Part.Builder... partsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder parts(Optional> parts); + + /** Clears the value of parts field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearParts() { + return parts(Optional.empty()); + } + /** * 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. + *

    role: Optional. The producer of the content. Must be either 'user' or 'model'. If not set, + * the service will default to 'user'. */ @JsonProperty("role") public abstract Builder role(String role); + @ExcludeFromGeneratedCoverageReport + abstract Builder role(Optional role); + + /** Clears the value of role field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearRole() { + return role(Optional.empty()); + } + public abstract Content build(); } /** 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..30a64578823 100644 --- a/src/main/java/com/google/genai/types/ContentEmbedding.java +++ b/src/main/java/com/google/genai/types/ContentEmbedding.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.Arrays; import java.util.List; @@ -35,11 +36,15 @@ public abstract class ContentEmbedding extends JsonSerializable { @JsonProperty("values") public abstract Optional> values(); - /** Vertex API only. Statistics of the input text associated with this embedding. */ + /** + * Gemini Enterprise Agent Platform only. Statistics of the input text associated with this + * embedding. + */ @JsonProperty("statistics") public abstract Optional statistics(); /** Instantiates a builder for ContentEmbedding. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ContentEmbedding.Builder(); } @@ -69,14 +74,26 @@ private static Builder create() { * *

    values: A list of floats representing an embedding. */ + @CanIgnoreReturnValue public Builder values(Float... values) { return values(Arrays.asList(values)); } + @ExcludeFromGeneratedCoverageReport + abstract Builder values(Optional> values); + + /** Clears the value of values field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearValues() { + return values(Optional.empty()); + } + /** * Setter for statistics. * - *

    statistics: Vertex API only. Statistics of the input text associated with this embedding. + *

    statistics: Gemini Enterprise Agent Platform only. Statistics of the input text associated + * with this embedding. */ @JsonProperty("statistics") public abstract Builder statistics(ContentEmbeddingStatistics statistics); @@ -84,16 +101,29 @@ public Builder values(Float... values) { /** * Setter for statistics builder. * - *

    statistics: Vertex API only. Statistics of the input text associated with this embedding. + *

    statistics: Gemini Enterprise Agent Platform only. Statistics of the input text associated + * with this embedding. */ + @CanIgnoreReturnValue public Builder statistics(ContentEmbeddingStatistics.Builder statisticsBuilder) { return statistics(statisticsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder statistics(Optional statistics); + + /** Clears the value of statistics field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearStatistics() { + return statistics(Optional.empty()); + } + public abstract ContentEmbedding build(); } /** 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..1aabea9b772 100644 --- a/src/main/java/com/google/genai/types/ContentEmbeddingStatistics.java +++ b/src/main/java/com/google/genai/types/ContentEmbeddingStatistics.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; @@ -30,17 +31,18 @@ @JsonDeserialize(builder = ContentEmbeddingStatistics.Builder.class) public abstract class ContentEmbeddingStatistics extends JsonSerializable { /** - * Vertex API only. If the input text was truncated due to having a length longer than the allowed - * maximum input. + * Gemini Enterprise Agent Platform only. If the input text was truncated due to having a length + * longer than the allowed maximum input. */ @JsonProperty("truncated") public abstract Optional truncated(); - /** Vertex API only. Number of tokens of the input text. */ + /** Gemini Enterprise Agent Platform only. Number of tokens of the input text. */ @JsonProperty("tokenCount") public abstract Optional tokenCount(); /** Instantiates a builder for ContentEmbeddingStatistics. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ContentEmbeddingStatistics.Builder(); } @@ -60,24 +62,45 @@ private static Builder create() { /** * Setter for truncated. * - *

    truncated: Vertex API only. If the input text was truncated due to having a length longer - * than the allowed maximum input. + *

    truncated: Gemini Enterprise Agent Platform only. If the input text was truncated due to + * having a length longer than the allowed maximum input. */ @JsonProperty("truncated") public abstract Builder truncated(boolean truncated); + @ExcludeFromGeneratedCoverageReport + abstract Builder truncated(Optional truncated); + + /** Clears the value of truncated field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTruncated() { + return truncated(Optional.empty()); + } + /** * Setter for tokenCount. * - *

    tokenCount: Vertex API only. Number of tokens of the input text. + *

    tokenCount: Gemini Enterprise Agent Platform only. Number of tokens of the input text. */ @JsonProperty("tokenCount") public abstract Builder tokenCount(Float tokenCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder tokenCount(Optional tokenCount); + + /** Clears the value of tokenCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTokenCount() { + return tokenCount(Optional.empty()); + } + public abstract ContentEmbeddingStatistics build(); } /** 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..a1146eef5ad --- /dev/null +++ b/src/main/java/com/google/genai/types/ContentReferenceImage.java @@ -0,0 +1,150 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 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 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. + */ + @CanIgnoreReturnValue + public Builder referenceImage(Image.Builder referenceImageBuilder) { + return referenceImage(referenceImageBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder referenceImage(Optional referenceImage); + + /** Clears the value of referenceImage field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearReferenceImage() { + return referenceImage(Optional.empty()); + } + + /** + * Setter for referenceId. + * + *

    referenceId: The id of the reference image. + */ + @JsonProperty("referenceId") + public abstract Builder referenceId(Integer referenceId); + + @ExcludeFromGeneratedCoverageReport + abstract Builder referenceId(Optional referenceId); + + /** Clears the value of referenceId field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearReferenceId() { + return referenceId(Optional.empty()); + } + + /** + * Setter for referenceType. + * + *

    referenceType: The type of the reference image. Only set by the SDK. + */ + @JsonProperty("referenceType") + public abstract Builder referenceType(String referenceType); + + @ExcludeFromGeneratedCoverageReport + abstract Builder referenceType(Optional referenceType); + + /** Clears the value of referenceType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearReferenceType() { + return referenceType(Optional.empty()); + } + + 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..5e3e34ffdd3 100644 --- a/src/main/java/com/google/genai/types/ContextWindowCompressionConfig.java +++ b/src/main/java/com/google/genai/types/ContextWindowCompressionConfig.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; @@ -41,6 +42,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(); } @@ -68,6 +70,16 @@ private static Builder create() { @JsonProperty("triggerTokens") public abstract Builder triggerTokens(Long triggerTokens); + @ExcludeFromGeneratedCoverageReport + abstract Builder triggerTokens(Optional triggerTokens); + + /** Clears the value of triggerTokens field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTriggerTokens() { + return triggerTokens(Optional.empty()); + } + /** * Setter for slidingWindow. * @@ -81,14 +93,26 @@ private static Builder create() { * *

    slidingWindow: Sliding window compression mechanism. */ + @CanIgnoreReturnValue public Builder slidingWindow(SlidingWindow.Builder slidingWindowBuilder) { return slidingWindow(slidingWindowBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder slidingWindow(Optional slidingWindow); + + /** Clears the value of slidingWindow field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSlidingWindow() { + return slidingWindow(Optional.empty()); + } + public abstract ContextWindowCompressionConfig build(); } /** 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 90b773612d6..2f23964105a 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(); } @@ -66,15 +67,36 @@ private static Builder create() { @JsonProperty("controlType") public abstract Builder controlType(ControlReferenceType controlType); + @ExcludeFromGeneratedCoverageReport + abstract Builder controlType(Optional controlType); + + /** Clears the value of controlType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearControlType() { + return controlType(Optional.empty()); + } + + /** + * Setter for controlType given a known enum. + * + *

    controlType: The type of control reference image to use. + */ @CanIgnoreReturnValue public Builder controlType(ControlReferenceType.Known knownType) { return controlType(new ControlReferenceType(knownType)); } + /** + * Setter for controlType given a string. + * + *

    controlType: The type of control reference image to use. + */ @CanIgnoreReturnValue public Builder controlType(String controlType) { return controlType(new ControlReferenceType(controlType)); } + /** * Setter for enableControlImageComputation. * @@ -82,14 +104,24 @@ public Builder controlType(String controlType) { * be computed by the model based on the control type. When set to False, the control image must * be provided by the user. */ - @JsonProperty("enableControlImageComputation") public abstract Builder enableControlImageComputation(boolean enableControlImageComputation); + @ExcludeFromGeneratedCoverageReport + abstract Builder enableControlImageComputation(Optional enableControlImageComputation); + + /** Clears the value of enableControlImageComputation field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEnableControlImageComputation() { + return enableControlImageComputation(Optional.empty()); + } + public abstract ControlReferenceConfig build(); } /** 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..1d64f101a1b 100644 --- a/src/main/java/com/google/genai/types/ControlReferenceImage.java +++ b/src/main/java/com/google/genai/types/ControlReferenceImage.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; @@ -55,6 +56,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(); } @@ -84,10 +86,21 @@ private static Builder create() { * *

    referenceImage: The reference image for the editing operation. */ + @CanIgnoreReturnValue public Builder referenceImage(Image.Builder referenceImageBuilder) { return referenceImage(referenceImageBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder referenceImage(Optional referenceImage); + + /** Clears the value of referenceImage field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearReferenceImage() { + return referenceImage(Optional.empty()); + } + /** * Setter for referenceId. * @@ -96,6 +109,16 @@ public Builder referenceImage(Image.Builder referenceImageBuilder) { @JsonProperty("referenceId") public abstract Builder referenceId(Integer referenceId); + @ExcludeFromGeneratedCoverageReport + abstract Builder referenceId(Optional referenceId); + + /** Clears the value of referenceId field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearReferenceId() { + return referenceId(Optional.empty()); + } + /** * Setter for referenceType. * @@ -104,6 +127,16 @@ public Builder referenceImage(Image.Builder referenceImageBuilder) { @JsonProperty("referenceType") public abstract Builder referenceType(String referenceType); + @ExcludeFromGeneratedCoverageReport + abstract Builder referenceType(Optional referenceType); + + /** Clears the value of referenceType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearReferenceType() { + return referenceType(Optional.empty()); + } + /** * Setter for config. * @@ -117,14 +150,26 @@ public Builder referenceImage(Image.Builder referenceImageBuilder) { * *

    config: Configuration for the control reference image. */ + @CanIgnoreReturnValue public Builder config(ControlReferenceConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract ControlReferenceImage build(); } /** 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..b1edda35438 100644 --- a/src/main/java/com/google/genai/types/CountTokensConfig.java +++ b/src/main/java/com/google/genai/types/CountTokensConfig.java @@ -24,6 +24,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.Arrays; import java.util.List; @@ -56,6 +57,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(); } @@ -85,10 +87,21 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + /** * Setter for systemInstruction. * @@ -102,10 +115,21 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { * *

    systemInstruction: Instructions for the model to steer it toward better performance. */ + @CanIgnoreReturnValue public Builder systemInstruction(Content.Builder systemInstructionBuilder) { return systemInstruction(systemInstructionBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder systemInstruction(Optional systemInstruction); + + /** Clears the value of systemInstruction field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSystemInstruction() { + return systemInstruction(Optional.empty()); + } + /** * Setter for tools. * @@ -121,6 +145,7 @@ public Builder systemInstruction(Content.Builder systemInstructionBuilder) { *

    tools: Code that enables the system to interact with external systems to perform an action * outside of the knowledge and scope of the model. */ + @CanIgnoreReturnValue public Builder tools(Tool... tools) { return tools(Arrays.asList(tools)); } @@ -131,6 +156,7 @@ public Builder tools(Tool... tools) { *

    tools: Code that enables the system to interact with external systems to perform an action * outside of the knowledge and scope of the model. */ + @CanIgnoreReturnValue public Builder tools(Tool.Builder... toolsBuilders) { return tools( Arrays.asList(toolsBuilders).stream() @@ -138,6 +164,16 @@ public Builder tools(Tool.Builder... toolsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder tools(Optional> tools); + + /** Clears the value of tools field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTools() { + return tools(Optional.empty()); + } + /** * Setter for generationConfig. * @@ -153,14 +189,26 @@ public Builder tools(Tool.Builder... toolsBuilders) { *

    generationConfig: Configuration that the model uses to generate the response. Not * supported by the Gemini Developer API. */ + @CanIgnoreReturnValue public Builder generationConfig(GenerationConfig.Builder generationConfigBuilder) { return generationConfig(generationConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder generationConfig(Optional generationConfig); + + /** Clears the value of generationConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGenerationConfig() { + return generationConfig(Optional.empty()); + } + public abstract CountTokensConfig build(); } /** 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..4cc2ec68604 100644 --- a/src/main/java/com/google/genai/types/CountTokensParameters.java +++ b/src/main/java/com/google/genai/types/CountTokensParameters.java @@ -25,6 +25,7 @@ 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.Arrays; import java.util.List; @@ -51,6 +52,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(); } @@ -76,6 +78,16 @@ private static Builder create() { @JsonProperty("model") public abstract Builder model(String model); + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + /** * Setter for contents. * @@ -89,6 +101,7 @@ private static Builder create() { * *

    contents: Input content. */ + @CanIgnoreReturnValue public Builder contents(Content... contents) { return contents(Arrays.asList(contents)); } @@ -98,6 +111,7 @@ public Builder contents(Content... contents) { * *

    contents: Input content. */ + @CanIgnoreReturnValue public Builder contents(Content.Builder... contentsBuilders) { return contents( Arrays.asList(contentsBuilders).stream() @@ -105,6 +119,16 @@ public Builder contents(Content.Builder... contentsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder contents(Optional> contents); + + /** Clears the value of contents field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearContents() { + return contents(Optional.empty()); + } + /** * Setter for config. * @@ -118,14 +142,26 @@ public Builder contents(Content.Builder... contentsBuilders) { * *

    config: Configuration for counting tokens. */ + @CanIgnoreReturnValue public Builder config(CountTokensConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract CountTokensParameters build(); } /** 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..9e0daf42313 100644 --- a/src/main/java/com/google/genai/types/CountTokensResponse.java +++ b/src/main/java/com/google/genai/types/CountTokensResponse.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; @@ -29,6 +30,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 +43,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 +60,34 @@ 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. + */ + @CanIgnoreReturnValue + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + /** * Setter for totalTokens. * @@ -62,6 +96,16 @@ private static Builder create() { @JsonProperty("totalTokens") public abstract Builder totalTokens(Integer totalTokens); + @ExcludeFromGeneratedCoverageReport + abstract Builder totalTokens(Optional totalTokens); + + /** Clears the value of totalTokens field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTotalTokens() { + return totalTokens(Optional.empty()); + } + /** * Setter for cachedContentTokenCount. * @@ -71,10 +115,21 @@ private static Builder create() { @JsonProperty("cachedContentTokenCount") public abstract Builder cachedContentTokenCount(Integer cachedContentTokenCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder cachedContentTokenCount(Optional cachedContentTokenCount); + + /** Clears the value of cachedContentTokenCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCachedContentTokenCount() { + return cachedContentTokenCount(Optional.empty()); + } + public abstract CountTokensResponse build(); } /** 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/CountTokensResult.java b/src/main/java/com/google/genai/types/CountTokensResult.java new file mode 100644 index 00000000000..ae11ba72705 --- /dev/null +++ b/src/main/java/com/google/genai/types/CountTokensResult.java @@ -0,0 +1,81 @@ +/* + * 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; + +/** Local tokenizer count tokens result. */ +@AutoValue +@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 CountTokensResult. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CountTokensResult.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CountTokensResult. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CountTokensResult.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CountTokensResult.Builder(); + } + + /** + * Setter for totalTokens. + * + *

    totalTokens: The total number of tokens. + */ + @JsonProperty("totalTokens") + public abstract Builder totalTokens(Integer totalTokens); + + @ExcludeFromGeneratedCoverageReport + abstract Builder totalTokens(Optional totalTokens); + + /** Clears the value of totalTokens field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTotalTokens() { + return totalTokens(Optional.empty()); + } + + public abstract CountTokensResult build(); + } + + /** 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 index ec3e81c854c..29529e1cadf 100644 --- a/src/main/java/com/google/genai/types/CreateAuthTokenConfig.java +++ b/src/main/java/com/google/genai/types/CreateAuthTokenConfig.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.time.Instant; import java.util.Arrays; @@ -72,6 +73,7 @@ public abstract class CreateAuthTokenConfig extends JsonSerializable { public abstract Optional> lockAdditionalFields(); /** Instantiates a builder for CreateAuthTokenConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CreateAuthTokenConfig.Builder(); } @@ -101,10 +103,21 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + /** * Setter for expireTime. * @@ -117,6 +130,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("expireTime") public abstract Builder expireTime(Instant expireTime); + @ExcludeFromGeneratedCoverageReport + abstract Builder expireTime(Optional expireTime); + + /** Clears the value of expireTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearExpireTime() { + return expireTime(Optional.empty()); + } + /** * Setter for newSessionExpireTime. * @@ -129,6 +152,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("newSessionExpireTime") public abstract Builder newSessionExpireTime(Instant newSessionExpireTime); + @ExcludeFromGeneratedCoverageReport + abstract Builder newSessionExpireTime(Optional newSessionExpireTime); + + /** Clears the value of newSessionExpireTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearNewSessionExpireTime() { + return newSessionExpireTime(Optional.empty()); + } + /** * Setter for uses. * @@ -138,6 +171,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("uses") public abstract Builder uses(Integer uses); + @ExcludeFromGeneratedCoverageReport + abstract Builder uses(Optional uses); + + /** Clears the value of uses field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUses() { + return uses(Optional.empty()); + } + /** * Setter for liveConnectConstraints. * @@ -153,11 +196,23 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { *

    liveConnectConstraints: Configuration specific to Live API connections created using this * token. */ + @CanIgnoreReturnValue public Builder liveConnectConstraints( LiveConnectConstraints.Builder liveConnectConstraintsBuilder) { return liveConnectConstraints(liveConnectConstraintsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder liveConnectConstraints( + Optional liveConnectConstraints); + + /** Clears the value of liveConnectConstraints field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLiveConnectConstraints() { + return liveConnectConstraints(Optional.empty()); + } + /** * Setter for lockAdditionalFields. * @@ -171,14 +226,26 @@ public Builder liveConnectConstraints( * *

    lockAdditionalFields: Additional fields to lock in the effective LiveConnectParameters. */ + @CanIgnoreReturnValue public Builder lockAdditionalFields(String... lockAdditionalFields) { return lockAdditionalFields(Arrays.asList(lockAdditionalFields)); } + @ExcludeFromGeneratedCoverageReport + abstract Builder lockAdditionalFields(Optional> lockAdditionalFields); + + /** Clears the value of lockAdditionalFields field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLockAdditionalFields() { + return lockAdditionalFields(Optional.empty()); + } + public abstract CreateAuthTokenConfig build(); } /** Deserializes a JSON string to a CreateAuthTokenConfig object. */ + @ExcludeFromGeneratedCoverageReport 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 index e370fc951ff..1b7796d1407 100644 --- a/src/main/java/com/google/genai/types/CreateAuthTokenParameters.java +++ b/src/main/java/com/google/genai/types/CreateAuthTokenParameters.java @@ -23,6 +23,7 @@ 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; @@ -36,6 +37,7 @@ public abstract class CreateAuthTokenParameters extends JsonSerializable { public abstract Optional config(); /** Instantiates a builder for CreateAuthTokenParameters. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_CreateAuthTokenParameters.Builder(); } @@ -52,13 +54,39 @@ private static Builder create() { return new AutoValue_CreateAuthTokenParameters.Builder(); } + /** + * Setter for config. + * + *

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

    config: Optional parameters for the request. + */ + @CanIgnoreReturnValue + public Builder config(CreateAuthTokenConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract CreateAuthTokenParameters build(); } /** Deserializes a JSON string to a CreateAuthTokenParameters object. */ + @ExcludeFromGeneratedCoverageReport 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 new file mode 100644 index 00000000000..edd0192f135 --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateBatchJobConfig.java @@ -0,0 +1,184 @@ +/* + * 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; + +/** Config for optional parameters. */ +@AutoValue +@JsonDeserialize(builder = CreateBatchJobConfig.Builder.class) +public abstract class CreateBatchJobConfig 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(); + + /** + * GCS or BigQuery URI prefix for the output predictions. Example: "gs://path/to/output/data" or + * "bq://projectId.bqDatasetId.bqTableId". + */ + @JsonProperty("dest") + public abstract Optional dest(); + + /** Webhook configuration for receiving notifications when the batch operation completes. */ + @JsonProperty("webhookConfig") + public abstract Optional webhookConfig(); + + /** Instantiates a builder for CreateBatchJobConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CreateBatchJobConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CreateBatchJobConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CreateBatchJobConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CreateBatchJobConfig.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. + */ + @CanIgnoreReturnValue + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + + /** + * Setter for displayName. + * + *

    displayName: The user-defined name of this BatchJob. + */ + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + + /** + * Setter for dest. + * + *

    dest: GCS or BigQuery URI prefix for the output predictions. Example: + * "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + @JsonProperty("dest") + public abstract Builder dest(BatchJobDestination dest); + + /** + * Setter for dest builder. + * + *

    dest: GCS or BigQuery URI prefix for the output predictions. Example: + * "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + @CanIgnoreReturnValue + public Builder dest(BatchJobDestination.Builder destBuilder) { + return dest(destBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder dest(Optional dest); + + /** Clears the value of dest field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDest() { + return dest(Optional.empty()); + } + + /** + * Setter for webhookConfig. + * + *

    webhookConfig: Webhook configuration for receiving notifications when the batch operation + * completes. + */ + @JsonProperty("webhookConfig") + public abstract Builder webhookConfig(WebhookConfig webhookConfig); + + /** + * Setter for webhookConfig builder. + * + *

    webhookConfig: Webhook configuration for receiving notifications when the batch operation + * completes. + */ + @CanIgnoreReturnValue + public Builder webhookConfig(WebhookConfig.Builder webhookConfigBuilder) { + return webhookConfig(webhookConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder webhookConfig(Optional webhookConfig); + + /** Clears the value of webhookConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearWebhookConfig() { + return webhookConfig(Optional.empty()); + } + + public abstract CreateBatchJobConfig build(); + } + + /** 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 new file mode 100644 index 00000000000..83c36265a0d --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateBatchJobParameters.java @@ -0,0 +1,152 @@ +/* + * 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; + +/** Config for batches.create parameters. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = CreateBatchJobParameters.Builder.class) +public abstract class CreateBatchJobParameters extends JsonSerializable { + /** The name of the model to produces the predictions via the BatchJob. */ + @JsonProperty("model") + public abstract Optional model(); + + /** + * GCS URI(-s) or BigQuery URI to your input data to run batch job. Example: + * "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + @JsonProperty("src") + public abstract Optional src(); + + /** Optional parameters for creating a BatchJob. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for CreateBatchJobParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CreateBatchJobParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CreateBatchJobParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CreateBatchJobParameters.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CreateBatchJobParameters.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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + + /** + * Setter for src. + * + *

    src: GCS URI(-s) or BigQuery URI to your input data to run batch job. Example: + * "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + @JsonProperty("src") + public abstract Builder src(BatchJobSource src); + + /** + * Setter for src builder. + * + *

    src: GCS URI(-s) or BigQuery URI to your input data to run batch job. Example: + * "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + @CanIgnoreReturnValue + public Builder src(BatchJobSource.Builder srcBuilder) { + return src(srcBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder src(Optional src); + + /** Clears the value of src field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSrc() { + return src(Optional.empty()); + } + + /** + * Setter for config. + * + *

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

    config: Optional parameters for creating a BatchJob. + */ + @CanIgnoreReturnValue + public Builder config(CreateBatchJobConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + public abstract CreateBatchJobParameters build(); + } + + /** 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..47745664cdf 100644 --- a/src/main/java/com/google/genai/types/CreateCachedContentConfig.java +++ b/src/main/java/com/google/genai/types/CreateCachedContentConfig.java @@ -24,6 +24,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.time.Duration; import java.time.Instant; @@ -84,6 +85,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(); } @@ -113,10 +115,21 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + /** * Setter for ttl. * @@ -126,6 +139,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("ttl") public abstract Builder ttl(Duration ttl); + @ExcludeFromGeneratedCoverageReport + abstract Builder ttl(Optional ttl); + + /** Clears the value of ttl field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTtl() { + return ttl(Optional.empty()); + } + /** * Setter for expireTime. * @@ -135,6 +158,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("expireTime") public abstract Builder expireTime(Instant expireTime); + @ExcludeFromGeneratedCoverageReport + abstract Builder expireTime(Optional expireTime); + + /** Clears the value of expireTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearExpireTime() { + return expireTime(Optional.empty()); + } + /** * Setter for displayName. * @@ -143,6 +176,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("displayName") public abstract Builder displayName(String displayName); + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + /** * Setter for contents. * @@ -156,6 +199,7 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { * *

    contents: The content to cache. */ + @CanIgnoreReturnValue public Builder contents(Content... contents) { return contents(Arrays.asList(contents)); } @@ -165,6 +209,7 @@ public Builder contents(Content... contents) { * *

    contents: The content to cache. */ + @CanIgnoreReturnValue public Builder contents(Content.Builder... contentsBuilders) { return contents( Arrays.asList(contentsBuilders).stream() @@ -172,6 +217,16 @@ public Builder contents(Content.Builder... contentsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder contents(Optional> contents); + + /** Clears the value of contents field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearContents() { + return contents(Optional.empty()); + } + /** * Setter for systemInstruction. * @@ -185,10 +240,21 @@ public Builder contents(Content.Builder... contentsBuilders) { * *

    systemInstruction: Developer set system instruction. */ + @CanIgnoreReturnValue public Builder systemInstruction(Content.Builder systemInstructionBuilder) { return systemInstruction(systemInstructionBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder systemInstruction(Optional systemInstruction); + + /** Clears the value of systemInstruction field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSystemInstruction() { + return systemInstruction(Optional.empty()); + } + /** * Setter for tools. * @@ -202,6 +268,7 @@ public Builder systemInstruction(Content.Builder systemInstructionBuilder) { * *

    tools: A list of `Tools` the model may use to generate the next response. */ + @CanIgnoreReturnValue public Builder tools(Tool... tools) { return tools(Arrays.asList(tools)); } @@ -211,6 +278,7 @@ public Builder tools(Tool... tools) { * *

    tools: A list of `Tools` the model may use to generate the next response. */ + @CanIgnoreReturnValue public Builder tools(Tool.Builder... toolsBuilders) { return tools( Arrays.asList(toolsBuilders).stream() @@ -218,6 +286,16 @@ public Builder tools(Tool.Builder... toolsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder tools(Optional> tools); + + /** Clears the value of tools field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTools() { + return tools(Optional.empty()); + } + /** * Setter for toolConfig. * @@ -231,10 +309,21 @@ public Builder tools(Tool.Builder... toolsBuilders) { * *

    toolConfig: Configuration for the tools to use. This config is shared for all tools. */ + @CanIgnoreReturnValue public Builder toolConfig(ToolConfig.Builder toolConfigBuilder) { return toolConfig(toolConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder toolConfig(Optional toolConfig); + + /** Clears the value of toolConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearToolConfig() { + return toolConfig(Optional.empty()); + } + /** * Setter for kmsKeyName. * @@ -248,10 +337,21 @@ public Builder toolConfig(ToolConfig.Builder toolConfigBuilder) { @JsonProperty("kmsKeyName") public abstract Builder kmsKeyName(String kmsKeyName); + @ExcludeFromGeneratedCoverageReport + abstract Builder kmsKeyName(Optional kmsKeyName); + + /** Clears the value of kmsKeyName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearKmsKeyName() { + return kmsKeyName(Optional.empty()); + } + public abstract CreateCachedContentConfig build(); } /** 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..942eeb4bc05 100644 --- a/src/main/java/com/google/genai/types/CreateCachedContentParameters.java +++ b/src/main/java/com/google/genai/types/CreateCachedContentParameters.java @@ -23,6 +23,7 @@ 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; @@ -40,6 +41,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(); } @@ -66,6 +68,16 @@ private static Builder create() { @JsonProperty("model") public abstract Builder model(String model); + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + /** * Setter for config. * @@ -79,14 +91,26 @@ private static Builder create() { * *

    config: Configuration that contains optional parameters. */ + @CanIgnoreReturnValue public Builder config(CreateCachedContentConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract CreateCachedContentParameters build(); } /** 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..387f1d7efb7 --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateEmbeddingsBatchJobConfig.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. + */ + +// 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; + +/** 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. + */ + @CanIgnoreReturnValue + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + + /** + * Setter for displayName. + * + *

    displayName: The user-defined name of this BatchJob. + */ + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + + 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..7ea473d8809 --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateEmbeddingsBatchJobParameters.java @@ -0,0 +1,150 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 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; + +/** 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + + /** + * 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". + */ + @CanIgnoreReturnValue + public Builder src(EmbeddingsBatchJobSource.Builder srcBuilder) { + return src(srcBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder src(Optional src); + + /** Clears the value of src field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSrc() { + return src(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder config(CreateEmbeddingsBatchJobConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + 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..ab8cb38d89c 100644 --- a/src/main/java/com/google/genai/types/CreateFileConfig.java +++ b/src/main/java/com/google/genai/types/CreateFileConfig.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; @@ -38,6 +39,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(); } @@ -67,10 +69,21 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + /** * Setter for shouldReturnHttpResponse. * @@ -80,10 +93,21 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("shouldReturnHttpResponse") public abstract Builder shouldReturnHttpResponse(boolean shouldReturnHttpResponse); + @ExcludeFromGeneratedCoverageReport + abstract Builder shouldReturnHttpResponse(Optional shouldReturnHttpResponse); + + /** Clears the value of shouldReturnHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearShouldReturnHttpResponse() { + return shouldReturnHttpResponse(Optional.empty()); + } + public abstract CreateFileConfig build(); } /** 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..b475909f916 100644 --- a/src/main/java/com/google/genai/types/CreateFileParameters.java +++ b/src/main/java/com/google/genai/types/CreateFileParameters.java @@ -23,6 +23,7 @@ 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; @@ -44,6 +45,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(); } @@ -77,10 +79,21 @@ private static Builder create() { * provided. name: (Optional) The name of the file in the destination (e.g. * 'files/sample-image'). display_name: (Optional) The display name of the file. */ + @CanIgnoreReturnValue public Builder file(File.Builder fileBuilder) { return file(fileBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder file(Optional file); + + /** Clears the value of file field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFile() { + return file(Optional.empty()); + } + /** * Setter for config. * @@ -94,14 +107,26 @@ public Builder file(File.Builder fileBuilder) { * *

    config: Used to override the default configuration. */ + @CanIgnoreReturnValue public Builder config(CreateFileConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract CreateFileParameters build(); } /** 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..ee801e97974 100644 --- a/src/main/java/com/google/genai/types/CreateFileResponse.java +++ b/src/main/java/com/google/genai/types/CreateFileResponse.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; @@ -34,6 +35,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(); } @@ -63,14 +65,26 @@ private static Builder create() { * *

    sdkHttpResponse: Used to retain the full HTTP response. */ + @CanIgnoreReturnValue public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { return sdkHttpResponse(sdkHttpResponseBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + public abstract CreateFileResponse build(); } /** 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/CreateFileSearchStoreConfig.java b/src/main/java/com/google/genai/types/CreateFileSearchStoreConfig.java new file mode 100644 index 00000000000..f44286d5df7 --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateFileSearchStoreConfig.java @@ -0,0 +1,139 @@ +/* + * 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; + +/** Optional parameters for creating a file search store. */ +@AutoValue +@JsonDeserialize(builder = CreateFileSearchStoreConfig.Builder.class) +public abstract class CreateFileSearchStoreConfig extends JsonSerializable { + /** Used to override HTTP request options. */ + @JsonProperty("httpOptions") + public abstract Optional httpOptions(); + + /** The human-readable display name for the file search store. */ + @JsonProperty("displayName") + public abstract Optional displayName(); + + /** + * The embedding model to use for the FileSearchStore. Format: `models/{model}`. If not specified, + * the default embedding model will be used. + */ + @JsonProperty("embeddingModel") + public abstract Optional embeddingModel(); + + /** Instantiates a builder for CreateFileSearchStoreConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CreateFileSearchStoreConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CreateFileSearchStoreConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CreateFileSearchStoreConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CreateFileSearchStoreConfig.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. + */ + @CanIgnoreReturnValue + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + + /** + * Setter for displayName. + * + *

    displayName: The human-readable display name for the file search store. + */ + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + + /** + * Setter for embeddingModel. + * + *

    embeddingModel: The embedding model to use for the FileSearchStore. Format: + * `models/{model}`. If not specified, the default embedding model will be used. + */ + @JsonProperty("embeddingModel") + public abstract Builder embeddingModel(String embeddingModel); + + @ExcludeFromGeneratedCoverageReport + abstract Builder embeddingModel(Optional embeddingModel); + + /** Clears the value of embeddingModel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEmbeddingModel() { + return embeddingModel(Optional.empty()); + } + + public abstract CreateFileSearchStoreConfig build(); + } + + /** Deserializes a JSON string to a CreateFileSearchStoreConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static CreateFileSearchStoreConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CreateFileSearchStoreConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/CreateFileSearchStoreParameters.java b/src/main/java/com/google/genai/types/CreateFileSearchStoreParameters.java new file mode 100644 index 00000000000..31db0434ef7 --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateFileSearchStoreParameters.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 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; + +/** Config for file_search_stores.create parameters. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = CreateFileSearchStoreParameters.Builder.class) +public abstract class CreateFileSearchStoreParameters extends JsonSerializable { + /** Optional parameters for creating a file search store. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for CreateFileSearchStoreParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CreateFileSearchStoreParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CreateFileSearchStoreParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `CreateFileSearchStoreParameters.builder()` for instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_CreateFileSearchStoreParameters.Builder(); + } + + /** + * Setter for config. + * + *

    config: Optional parameters for creating a file search store. + */ + @JsonProperty("config") + public abstract Builder config(CreateFileSearchStoreConfig config); + + /** + * Setter for config builder. + * + *

    config: Optional parameters for creating a file search store. + */ + @CanIgnoreReturnValue + public Builder config(CreateFileSearchStoreConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + public abstract CreateFileSearchStoreParameters build(); + } + + /** Deserializes a JSON string to a CreateFileSearchStoreParameters object. */ + @ExcludeFromGeneratedCoverageReport + public static CreateFileSearchStoreParameters fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CreateFileSearchStoreParameters.class); + } +} diff --git a/src/main/java/com/google/genai/types/CreateTuningJobConfig.java b/src/main/java/com/google/genai/types/CreateTuningJobConfig.java new file mode 100644 index 00000000000..7f446547c99 --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateTuningJobConfig.java @@ -0,0 +1,697 @@ +/* + * 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; + +/** Fine-tuning job creation request - optional fields. */ +@AutoValue +@JsonDeserialize(builder = CreateTuningJobConfig.Builder.class) +public abstract class CreateTuningJobConfig extends JsonSerializable { + /** Used to override HTTP request options. */ + @JsonProperty("httpOptions") + public abstract Optional httpOptions(); + + /** + * The method to use for tuning (SUPERVISED_FINE_TUNING or PREFERENCE_TUNING or DISTILLATION). 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(); + + /** + * The display name of the tuned Model. The name can be up to 128 characters long and can consist + * of any UTF-8 characters. + */ + @JsonProperty("tunedModelDisplayName") + public abstract Optional tunedModelDisplayName(); + + /** The description of the TuningJob */ + @JsonProperty("description") + public abstract Optional description(); + + /** Number of complete passes the model makes over the entire training dataset during training. */ + @JsonProperty("epochCount") + public abstract Optional epochCount(); + + /** + * Multiplier for adjusting the default learning rate. 1P models only. Mutually exclusive with + * learning_rate. + */ + @JsonProperty("learningRateMultiplier") + public abstract Optional learningRateMultiplier(); + + /** + * 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(); + + /** Tuning mode for tuning. */ + @JsonProperty("tuningMode") + public abstract Optional tuningMode(); + + /** + * Custom base model for tuning. This is only supported for OSS models in Gemini Enterprise Agent + * Platform. + */ + @JsonProperty("customBaseModel") + public abstract Optional customBaseModel(); + + /** + * The batch size hyperparameter for tuning. This is only supported for OSS models in Gemini + * Enterprise Agent Platform. + */ + @JsonProperty("batchSize") + public abstract Optional batchSize(); + + /** + * The learning rate for tuning. OSS models only. Mutually exclusive with + * learning_rate_multiplier. + */ + @JsonProperty("learningRate") + public abstract Optional learningRate(); + + /** Evaluation config for the tuning job. */ + @JsonProperty("evaluationConfig") + public abstract Optional evaluationConfig(); + + /** + * 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(); + + /** The base teacher model that is being distilled. Distillation only. */ + @JsonProperty("baseTeacherModel") + public abstract Optional baseTeacherModel(); + + /** The resource name of the Tuned teacher model. Distillation only. */ + @JsonProperty("tunedTeacherModelSource") + public abstract Optional tunedTeacherModelSource(); + + /** Multiplier for adjusting the weight of the SFT loss. Distillation only. */ + @JsonProperty("sftLossWeightMultiplier") + public abstract Optional sftLossWeightMultiplier(); + + /** The Google Cloud Storage location where the tuning job outputs are written. */ + @JsonProperty("outputUri") + public abstract Optional outputUri(); + + /** + * The encryption spec of the tuning job. Customer-managed encryption key options for a TuningJob. + * If this is set, then all resources created by the TuningJob will be encrypted with provided + * encryption key. + */ + @JsonProperty("encryptionSpec") + public abstract Optional encryptionSpec(); + + /** Instantiates a builder for CreateTuningJobConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CreateTuningJobConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CreateTuningJobConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CreateTuningJobConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CreateTuningJobConfig.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. + */ + @CanIgnoreReturnValue + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + + /** + * Setter for method. + * + *

    method: The method to use for tuning (SUPERVISED_FINE_TUNING or PREFERENCE_TUNING or + * DISTILLATION). If not set, the default method (SFT) will be used. + */ + @JsonProperty("method") + public abstract Builder method(TuningMethod method); + + @ExcludeFromGeneratedCoverageReport + abstract Builder method(Optional method); + + /** Clears the value of method field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMethod() { + return method(Optional.empty()); + } + + /** + * Setter for method given a known enum. + * + *

    method: The method to use for tuning (SUPERVISED_FINE_TUNING or PREFERENCE_TUNING or + * DISTILLATION). 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 or + * DISTILLATION). 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: Validation dataset for tuning. The dataset must be formatted as a JSONL + * file. + */ + @JsonProperty("validationDataset") + public abstract Builder validationDataset(TuningValidationDataset validationDataset); + + /** + * Setter for validationDataset builder. + * + *

    validationDataset: Validation dataset for tuning. The dataset must be formatted as a JSONL + * file. + */ + @CanIgnoreReturnValue + public Builder validationDataset(TuningValidationDataset.Builder validationDatasetBuilder) { + return validationDataset(validationDatasetBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder validationDataset(Optional validationDataset); + + /** Clears the value of validationDataset field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearValidationDataset() { + return validationDataset(Optional.empty()); + } + + /** + * Setter for tunedModelDisplayName. + * + *

    tunedModelDisplayName: The display name of the tuned Model. The name can be up to 128 + * characters long and can consist of any UTF-8 characters. + */ + @JsonProperty("tunedModelDisplayName") + public abstract Builder tunedModelDisplayName(String tunedModelDisplayName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder tunedModelDisplayName(Optional tunedModelDisplayName); + + /** Clears the value of tunedModelDisplayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTunedModelDisplayName() { + return tunedModelDisplayName(Optional.empty()); + } + + /** + * Setter for description. + * + *

    description: The description of the TuningJob + */ + @JsonProperty("description") + public abstract Builder description(String description); + + @ExcludeFromGeneratedCoverageReport + abstract Builder description(Optional description); + + /** Clears the value of description field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDescription() { + return description(Optional.empty()); + } + + /** + * Setter for epochCount. + * + *

    epochCount: Number of complete passes the model makes over the entire training dataset + * during training. + */ + @JsonProperty("epochCount") + public abstract Builder epochCount(Integer epochCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder epochCount(Optional epochCount); + + /** Clears the value of epochCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEpochCount() { + return epochCount(Optional.empty()); + } + + /** + * Setter for learningRateMultiplier. + * + *

    learningRateMultiplier: Multiplier for adjusting the default learning rate. 1P models + * only. Mutually exclusive with learning_rate. + */ + @JsonProperty("learningRateMultiplier") + public abstract Builder learningRateMultiplier(Float learningRateMultiplier); + + @ExcludeFromGeneratedCoverageReport + abstract Builder learningRateMultiplier(Optional learningRateMultiplier); + + /** Clears the value of learningRateMultiplier field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLearningRateMultiplier() { + return learningRateMultiplier(Optional.empty()); + } + + /** + * Setter for exportLastCheckpointOnly. + * + *

    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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder exportLastCheckpointOnly(Optional exportLastCheckpointOnly); + + /** Clears the value of exportLastCheckpointOnly field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearExportLastCheckpointOnly() { + return exportLastCheckpointOnly(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder preTunedModelCheckpointId(Optional preTunedModelCheckpointId); + + /** Clears the value of preTunedModelCheckpointId field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPreTunedModelCheckpointId() { + return preTunedModelCheckpointId(Optional.empty()); + } + + /** + * Setter for adapterSize. + * + *

    adapterSize: Adapter size for tuning. + */ + @JsonProperty("adapterSize") + public abstract Builder adapterSize(AdapterSize adapterSize); + + @ExcludeFromGeneratedCoverageReport + abstract Builder adapterSize(Optional adapterSize); + + /** Clears the value of adapterSize field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAdapterSize() { + return adapterSize(Optional.empty()); + } + + /** + * Setter for adapterSize given a known enum. + * + *

    adapterSize: Adapter size for tuning. + */ + @CanIgnoreReturnValue + public Builder adapterSize(AdapterSize.Known knownType) { + return adapterSize(new AdapterSize(knownType)); + } + + /** + * Setter for adapterSize given a string. + * + *

    adapterSize: Adapter size for tuning. + */ + @CanIgnoreReturnValue + public Builder adapterSize(String adapterSize) { + return adapterSize(new AdapterSize(adapterSize)); + } + + /** + * Setter for tuningMode. + * + *

    tuningMode: Tuning mode for tuning. + */ + @JsonProperty("tuningMode") + public abstract Builder tuningMode(TuningMode tuningMode); + + @ExcludeFromGeneratedCoverageReport + abstract Builder tuningMode(Optional tuningMode); + + /** Clears the value of tuningMode field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTuningMode() { + return tuningMode(Optional.empty()); + } + + /** + * Setter for tuningMode given a known enum. + * + *

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

    tuningMode: Tuning mode for tuning. + */ + @CanIgnoreReturnValue + public Builder tuningMode(String tuningMode) { + return tuningMode(new TuningMode(tuningMode)); + } + + /** + * Setter for customBaseModel. + * + *

    customBaseModel: Custom base model for tuning. This is only supported for OSS models in + * Gemini Enterprise Agent Platform. + */ + @JsonProperty("customBaseModel") + public abstract Builder customBaseModel(String customBaseModel); + + @ExcludeFromGeneratedCoverageReport + abstract Builder customBaseModel(Optional customBaseModel); + + /** Clears the value of customBaseModel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCustomBaseModel() { + return customBaseModel(Optional.empty()); + } + + /** + * Setter for batchSize. + * + *

    batchSize: The batch size hyperparameter for tuning. This is only supported for OSS models + * in Gemini Enterprise Agent Platform. + */ + @JsonProperty("batchSize") + public abstract Builder batchSize(Integer batchSize); + + @ExcludeFromGeneratedCoverageReport + abstract Builder batchSize(Optional batchSize); + + /** Clears the value of batchSize field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBatchSize() { + return batchSize(Optional.empty()); + } + + /** + * Setter for learningRate. + * + *

    learningRate: The learning rate for tuning. OSS models only. Mutually exclusive with + * learning_rate_multiplier. + */ + @JsonProperty("learningRate") + public abstract Builder learningRate(Float learningRate); + + @ExcludeFromGeneratedCoverageReport + abstract Builder learningRate(Optional learningRate); + + /** Clears the value of learningRate field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLearningRate() { + return learningRate(Optional.empty()); + } + + /** + * Setter for evaluationConfig. + * + *

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

    evaluationConfig: Evaluation config for the tuning job. + */ + @CanIgnoreReturnValue + public Builder evaluationConfig(EvaluationConfig.Builder evaluationConfigBuilder) { + return evaluationConfig(evaluationConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder evaluationConfig(Optional evaluationConfig); + + /** Clears the value of evaluationConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEvaluationConfig() { + return evaluationConfig(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder labels(Optional> labels); + + /** Clears the value of labels field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLabels() { + return labels(Optional.empty()); + } + + /** + * Setter for beta. + * + *

    beta: Weight for KL Divergence regularization, Preference Optimization tuning only. + */ + @JsonProperty("beta") + public abstract Builder beta(Float beta); + + @ExcludeFromGeneratedCoverageReport + abstract Builder beta(Optional beta); + + /** Clears the value of beta field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBeta() { + return beta(Optional.empty()); + } + + /** + * Setter for baseTeacherModel. + * + *

    baseTeacherModel: The base teacher model that is being distilled. Distillation only. + */ + @JsonProperty("baseTeacherModel") + public abstract Builder baseTeacherModel(String baseTeacherModel); + + @ExcludeFromGeneratedCoverageReport + abstract Builder baseTeacherModel(Optional baseTeacherModel); + + /** Clears the value of baseTeacherModel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBaseTeacherModel() { + return baseTeacherModel(Optional.empty()); + } + + /** + * Setter for tunedTeacherModelSource. + * + *

    tunedTeacherModelSource: The resource name of the Tuned teacher model. Distillation only. + */ + @JsonProperty("tunedTeacherModelSource") + public abstract Builder tunedTeacherModelSource(String tunedTeacherModelSource); + + @ExcludeFromGeneratedCoverageReport + abstract Builder tunedTeacherModelSource(Optional tunedTeacherModelSource); + + /** Clears the value of tunedTeacherModelSource field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTunedTeacherModelSource() { + return tunedTeacherModelSource(Optional.empty()); + } + + /** + * Setter for sftLossWeightMultiplier. + * + *

    sftLossWeightMultiplier: Multiplier for adjusting the weight of the SFT loss. Distillation + * only. + */ + @JsonProperty("sftLossWeightMultiplier") + public abstract Builder sftLossWeightMultiplier(Float sftLossWeightMultiplier); + + @ExcludeFromGeneratedCoverageReport + abstract Builder sftLossWeightMultiplier(Optional sftLossWeightMultiplier); + + /** Clears the value of sftLossWeightMultiplier field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSftLossWeightMultiplier() { + return sftLossWeightMultiplier(Optional.empty()); + } + + /** + * Setter for outputUri. + * + *

    outputUri: The Google Cloud Storage location where the tuning job outputs are written. + */ + @JsonProperty("outputUri") + public abstract Builder outputUri(String outputUri); + + @ExcludeFromGeneratedCoverageReport + abstract Builder outputUri(Optional outputUri); + + /** Clears the value of outputUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputUri() { + return outputUri(Optional.empty()); + } + + /** + * Setter for encryptionSpec. + * + *

    encryptionSpec: The encryption spec of the tuning job. Customer-managed encryption key + * options for a TuningJob. If this is set, then all resources created by the TuningJob will be + * encrypted with provided encryption key. + */ + @JsonProperty("encryptionSpec") + public abstract Builder encryptionSpec(EncryptionSpec encryptionSpec); + + /** + * Setter for encryptionSpec builder. + * + *

    encryptionSpec: The encryption spec of the tuning job. Customer-managed encryption key + * options for a TuningJob. If this is set, then all resources created by the TuningJob will be + * encrypted with provided encryption key. + */ + @CanIgnoreReturnValue + public Builder encryptionSpec(EncryptionSpec.Builder encryptionSpecBuilder) { + return encryptionSpec(encryptionSpecBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder encryptionSpec(Optional encryptionSpec); + + /** Clears the value of encryptionSpec field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEncryptionSpec() { + return encryptionSpec(Optional.empty()); + } + + 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 new file mode 100644 index 00000000000..f0f49ddfef1 --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateTuningJobParameters.java @@ -0,0 +1,152 @@ +/* + * 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; + +/** 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-2.5-flash". */ + @JsonProperty("baseModel") + public abstract Optional baseModel(); + + /** + * 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 CreateTuningJobParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CreateTuningJobParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CreateTuningJobParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CreateTuningJobParameters.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CreateTuningJobParameters.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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder baseModel(Optional baseModel); + + /** Clears the value of baseModel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBaseModel() { + return baseModel(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder trainingDataset(TuningDataset.Builder trainingDatasetBuilder) { + return trainingDataset(trainingDatasetBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder trainingDataset(Optional trainingDataset); + + /** Clears the value of trainingDataset field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTrainingDataset() { + return trainingDataset(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder config(CreateTuningJobConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + public abstract CreateTuningJobParameters build(); + } + + /** 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..68ee15ace01 --- /dev/null +++ b/src/main/java/com/google/genai/types/CreateTuningJobParametersPrivate.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.api.core.InternalApi; +import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder baseModel(Optional baseModel); + + /** Clears the value of baseModel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBaseModel() { + return baseModel(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder preTunedModel(PreTunedModel.Builder preTunedModelBuilder) { + return preTunedModel(preTunedModelBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder preTunedModel(Optional preTunedModel); + + /** Clears the value of preTunedModel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPreTunedModel() { + return preTunedModel(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder trainingDataset(TuningDataset.Builder trainingDatasetBuilder) { + return trainingDataset(trainingDatasetBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder trainingDataset(Optional trainingDataset); + + /** Clears the value of trainingDataset field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTrainingDataset() { + return trainingDataset(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder config(CreateTuningJobConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + 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/CustomCodeExecutionResult.java b/src/main/java/com/google/genai/types/CustomCodeExecutionResult.java new file mode 100644 index 00000000000..f3a740e13e5 --- /dev/null +++ b/src/main/java/com/google/genai/types/CustomCodeExecutionResult.java @@ -0,0 +1,81 @@ +/* + * 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; + +/** Result for custom code execution metric. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = CustomCodeExecutionResult.Builder.class) +public abstract class CustomCodeExecutionResult extends JsonSerializable { + /** Output only. Custom code execution score. */ + @JsonProperty("score") + public abstract Optional score(); + + /** Instantiates a builder for CustomCodeExecutionResult. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CustomCodeExecutionResult.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CustomCodeExecutionResult. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CustomCodeExecutionResult.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CustomCodeExecutionResult.Builder(); + } + + /** + * Setter for score. + * + *

    score: Output only. Custom code execution score. + */ + @JsonProperty("score") + public abstract Builder score(Float score); + + @ExcludeFromGeneratedCoverageReport + abstract Builder score(Optional score); + + /** Clears the value of score field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearScore() { + return score(Optional.empty()); + } + + public abstract CustomCodeExecutionResult build(); + } + + /** Deserializes a JSON string to a CustomCodeExecutionResult object. */ + @ExcludeFromGeneratedCoverageReport + public static CustomCodeExecutionResult fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CustomCodeExecutionResult.class); + } +} diff --git a/src/main/java/com/google/genai/types/CustomCodeExecutionSpec.java b/src/main/java/com/google/genai/types/CustomCodeExecutionSpec.java new file mode 100644 index 00000000000..1429b73f223 --- /dev/null +++ b/src/main/java/com/google/genai/types/CustomCodeExecutionSpec.java @@ -0,0 +1,90 @@ +/* + * 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; + +/** Specificies a metric that is computed by running user-defined Python functions remotely. */ +@AutoValue +@JsonDeserialize(builder = CustomCodeExecutionSpec.Builder.class) +public abstract class CustomCodeExecutionSpec extends JsonSerializable { + /** + * A string representing a user-defined function for evaluation. Expected user to define the + * following function, e.g.: def evaluate(instance: dict[str, Any]) -> float: Please include this + * function signature in the code snippet. Instance is the evaluation instance, any fields + * populated in the instance are available to the function as instance[field_name]. + */ + @JsonProperty("evaluationFunction") + public abstract Optional evaluationFunction(); + + /** Instantiates a builder for CustomCodeExecutionSpec. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CustomCodeExecutionSpec.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CustomCodeExecutionSpec. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CustomCodeExecutionSpec.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CustomCodeExecutionSpec.Builder(); + } + + /** + * Setter for evaluationFunction. + * + *

    evaluationFunction: A string representing a user-defined function for evaluation. Expected + * user to define the following function, e.g.: def evaluate(instance: dict[str, Any]) -> float: + * Please include this function signature in the code snippet. Instance is the evaluation + * instance, any fields populated in the instance are available to the function as + * instance[field_name]. + */ + @JsonProperty("evaluationFunction") + public abstract Builder evaluationFunction(String evaluationFunction); + + @ExcludeFromGeneratedCoverageReport + abstract Builder evaluationFunction(Optional evaluationFunction); + + /** Clears the value of evaluationFunction field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEvaluationFunction() { + return evaluationFunction(Optional.empty()); + } + + public abstract CustomCodeExecutionSpec build(); + } + + /** Deserializes a JSON string to a CustomCodeExecutionSpec object. */ + @ExcludeFromGeneratedCoverageReport + public static CustomCodeExecutionSpec fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CustomCodeExecutionSpec.class); + } +} diff --git a/src/main/java/com/google/genai/types/CustomMetadata.java b/src/main/java/com/google/genai/types/CustomMetadata.java new file mode 100644 index 00000000000..1e34b3bcc1d --- /dev/null +++ b/src/main/java/com/google/genai/types/CustomMetadata.java @@ -0,0 +1,159 @@ +/* + * 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; + +/** + * User provided metadata stored as key-value pairs. This data type is not supported in Vertex AI. + */ +@AutoValue +@JsonDeserialize(builder = CustomMetadata.Builder.class) +public abstract class CustomMetadata extends JsonSerializable { + /** Required. The key of the metadata to store. */ + @JsonProperty("key") + public abstract Optional key(); + + /** The numeric value of the metadata to store. */ + @JsonProperty("numericValue") + public abstract Optional numericValue(); + + /** The StringList value of the metadata to store. */ + @JsonProperty("stringListValue") + public abstract Optional stringListValue(); + + /** The string value of the metadata to store. */ + @JsonProperty("stringValue") + public abstract Optional stringValue(); + + /** Instantiates a builder for CustomMetadata. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CustomMetadata.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CustomMetadata. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CustomMetadata.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CustomMetadata.Builder(); + } + + /** + * Setter for key. + * + *

    key: Required. The key of the metadata to store. + */ + @JsonProperty("key") + public abstract Builder key(String key); + + @ExcludeFromGeneratedCoverageReport + abstract Builder key(Optional key); + + /** Clears the value of key field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearKey() { + return key(Optional.empty()); + } + + /** + * Setter for numericValue. + * + *

    numericValue: The numeric value of the metadata to store. + */ + @JsonProperty("numericValue") + public abstract Builder numericValue(Float numericValue); + + @ExcludeFromGeneratedCoverageReport + abstract Builder numericValue(Optional numericValue); + + /** Clears the value of numericValue field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearNumericValue() { + return numericValue(Optional.empty()); + } + + /** + * Setter for stringListValue. + * + *

    stringListValue: The StringList value of the metadata to store. + */ + @JsonProperty("stringListValue") + public abstract Builder stringListValue(StringList stringListValue); + + /** + * Setter for stringListValue builder. + * + *

    stringListValue: The StringList value of the metadata to store. + */ + @CanIgnoreReturnValue + public Builder stringListValue(StringList.Builder stringListValueBuilder) { + return stringListValue(stringListValueBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder stringListValue(Optional stringListValue); + + /** Clears the value of stringListValue field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearStringListValue() { + return stringListValue(Optional.empty()); + } + + /** + * Setter for stringValue. + * + *

    stringValue: The string value of the metadata to store. + */ + @JsonProperty("stringValue") + public abstract Builder stringValue(String stringValue); + + @ExcludeFromGeneratedCoverageReport + abstract Builder stringValue(Optional stringValue); + + /** Clears the value of stringValue field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearStringValue() { + return stringValue(Optional.empty()); + } + + public abstract CustomMetadata build(); + } + + /** Deserializes a JSON string to a CustomMetadata object. */ + @ExcludeFromGeneratedCoverageReport + public static CustomMetadata fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CustomMetadata.class); + } +} diff --git a/src/main/java/com/google/genai/types/CustomOutput.java b/src/main/java/com/google/genai/types/CustomOutput.java new file mode 100644 index 00000000000..6ab960e0dc9 --- /dev/null +++ b/src/main/java/com/google/genai/types/CustomOutput.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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Spec for custom output. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = CustomOutput.Builder.class) +public abstract class CustomOutput extends JsonSerializable { + /** Output only. List of raw output strings. */ + @JsonProperty("rawOutputs") + public abstract Optional rawOutputs(); + + /** Instantiates a builder for CustomOutput. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CustomOutput.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CustomOutput. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CustomOutput.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CustomOutput.Builder(); + } + + /** + * Setter for rawOutputs. + * + *

    rawOutputs: Output only. List of raw output strings. + */ + @JsonProperty("rawOutputs") + public abstract Builder rawOutputs(RawOutput rawOutputs); + + /** + * Setter for rawOutputs builder. + * + *

    rawOutputs: Output only. List of raw output strings. + */ + @CanIgnoreReturnValue + public Builder rawOutputs(RawOutput.Builder rawOutputsBuilder) { + return rawOutputs(rawOutputsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder rawOutputs(Optional rawOutputs); + + /** Clears the value of rawOutputs field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearRawOutputs() { + return rawOutputs(Optional.empty()); + } + + public abstract CustomOutput build(); + } + + /** Deserializes a JSON string to a CustomOutput object. */ + @ExcludeFromGeneratedCoverageReport + public static CustomOutput fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CustomOutput.class); + } +} diff --git a/src/main/java/com/google/genai/types/CustomOutputFormatConfig.java b/src/main/java/com/google/genai/types/CustomOutputFormatConfig.java new file mode 100644 index 00000000000..ea17ac88036 --- /dev/null +++ b/src/main/java/com/google/genai/types/CustomOutputFormatConfig.java @@ -0,0 +1,81 @@ +/* + * 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; + +/** Config for custom output format. */ +@AutoValue +@JsonDeserialize(builder = CustomOutputFormatConfig.Builder.class) +public abstract class CustomOutputFormatConfig extends JsonSerializable { + /** Optional. Whether to return raw output. */ + @JsonProperty("returnRawOutput") + public abstract Optional returnRawOutput(); + + /** Instantiates a builder for CustomOutputFormatConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CustomOutputFormatConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CustomOutputFormatConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CustomOutputFormatConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CustomOutputFormatConfig.Builder(); + } + + /** + * Setter for returnRawOutput. + * + *

    returnRawOutput: Optional. Whether to return raw output. + */ + @JsonProperty("returnRawOutput") + public abstract Builder returnRawOutput(boolean returnRawOutput); + + @ExcludeFromGeneratedCoverageReport + abstract Builder returnRawOutput(Optional returnRawOutput); + + /** Clears the value of returnRawOutput field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearReturnRawOutput() { + return returnRawOutput(Optional.empty()); + } + + public abstract CustomOutputFormatConfig build(); + } + + /** Deserializes a JSON string to a CustomOutputFormatConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static CustomOutputFormatConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CustomOutputFormatConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/CustomizedAvatar.java b/src/main/java/com/google/genai/types/CustomizedAvatar.java new file mode 100644 index 00000000000..20d72a7be32 --- /dev/null +++ b/src/main/java/com/google/genai/types/CustomizedAvatar.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. + */ + +// 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; + +/** Configures the customized avatar to be used in the session. */ +@AutoValue +@JsonDeserialize(builder = CustomizedAvatar.Builder.class) +public abstract class CustomizedAvatar extends JsonSerializable { + /** The mime type of the reference image, e.g., "image/jpeg". */ + @JsonProperty("imageMimeType") + public abstract Optional imageMimeType(); + + /** + * The data of the reference image. The dimensions of the reference image should be 9:16 + * (portrait) with a minimum resolution of 704x1280. + */ + @JsonProperty("imageData") + public abstract Optional imageData(); + + /** Instantiates a builder for CustomizedAvatar. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_CustomizedAvatar.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for CustomizedAvatar. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `CustomizedAvatar.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_CustomizedAvatar.Builder(); + } + + /** + * Setter for imageMimeType. + * + *

    imageMimeType: The mime type of the reference image, e.g., "image/jpeg". + */ + @JsonProperty("imageMimeType") + public abstract Builder imageMimeType(String imageMimeType); + + @ExcludeFromGeneratedCoverageReport + abstract Builder imageMimeType(Optional imageMimeType); + + /** Clears the value of imageMimeType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearImageMimeType() { + return imageMimeType(Optional.empty()); + } + + /** + * Setter for imageData. + * + *

    imageData: The data of the reference image. The dimensions of the reference image should + * be 9:16 (portrait) with a minimum resolution of 704x1280. + */ + @JsonProperty("imageData") + public abstract Builder imageData(byte[] imageData); + + @ExcludeFromGeneratedCoverageReport + abstract Builder imageData(Optional imageData); + + /** Clears the value of imageData field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearImageData() { + return imageData(Optional.empty()); + } + + public abstract CustomizedAvatar build(); + } + + /** Deserializes a JSON string to a CustomizedAvatar object. */ + @ExcludeFromGeneratedCoverageReport + public static CustomizedAvatar fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, CustomizedAvatar.class); + } +} diff --git a/src/main/java/com/google/genai/types/DatasetDistribution.java b/src/main/java/com/google/genai/types/DatasetDistribution.java new file mode 100644 index 00000000000..2b38c042014 --- /dev/null +++ b/src/main/java/com/google/genai/types/DatasetDistribution.java @@ -0,0 +1,262 @@ +/* + * 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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** 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 { + /** Output only. Defines the histogram bucket. */ + @JsonProperty("buckets") + public abstract Optional> buckets(); + + /** Output only. The maximum of the population values. */ + @JsonProperty("max") + public abstract Optional max(); + + /** Output only. The arithmetic mean of the values in the population. */ + @JsonProperty("mean") + public abstract Optional mean(); + + /** Output only. The median of the values in the population. */ + @JsonProperty("median") + public abstract Optional median(); + + /** Output only. The minimum of the population values. */ + @JsonProperty("min") + public abstract Optional min(); + + /** Output only. The 5th percentile of the values in the population. */ + @JsonProperty("p5") + public abstract Optional p5(); + + /** Output only. The 95th percentile of the values in the population. */ + @JsonProperty("p95") + public abstract Optional p95(); + + /** Output only. Sum of a given population of values. */ + @JsonProperty("sum") + public abstract Optional sum(); + + /** Instantiates a builder for DatasetDistribution. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DatasetDistribution.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DatasetDistribution. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DatasetDistribution.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_DatasetDistribution.Builder(); + } + + /** + * Setter for buckets. + * + *

    buckets: Output only. Defines the histogram bucket. + */ + @JsonProperty("buckets") + public abstract Builder buckets(List buckets); + + /** + * Setter for buckets. + * + *

    buckets: Output only. Defines the histogram bucket. + */ + @CanIgnoreReturnValue + public Builder buckets(DatasetDistributionDistributionBucket... buckets) { + return buckets(Arrays.asList(buckets)); + } + + /** + * Setter for buckets builder. + * + *

    buckets: Output only. Defines the histogram bucket. + */ + @CanIgnoreReturnValue + public Builder buckets(DatasetDistributionDistributionBucket.Builder... bucketsBuilders) { + return buckets( + Arrays.asList(bucketsBuilders).stream() + .map(DatasetDistributionDistributionBucket.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder buckets(Optional> buckets); + + /** Clears the value of buckets field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBuckets() { + return buckets(Optional.empty()); + } + + /** + * Setter for max. + * + *

    max: Output only. The maximum of the population values. + */ + @JsonProperty("max") + public abstract Builder max(Double max); + + @ExcludeFromGeneratedCoverageReport + abstract Builder max(Optional max); + + /** Clears the value of max field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMax() { + return max(Optional.empty()); + } + + /** + * Setter for mean. + * + *

    mean: Output only. The arithmetic mean of the values in the population. + */ + @JsonProperty("mean") + public abstract Builder mean(Double mean); + + @ExcludeFromGeneratedCoverageReport + abstract Builder mean(Optional mean); + + /** Clears the value of mean field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMean() { + return mean(Optional.empty()); + } + + /** + * Setter for median. + * + *

    median: Output only. The median of the values in the population. + */ + @JsonProperty("median") + public abstract Builder median(Double median); + + @ExcludeFromGeneratedCoverageReport + abstract Builder median(Optional median); + + /** Clears the value of median field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMedian() { + return median(Optional.empty()); + } + + /** + * Setter for min. + * + *

    min: Output only. The minimum of the population values. + */ + @JsonProperty("min") + public abstract Builder min(Double min); + + @ExcludeFromGeneratedCoverageReport + abstract Builder min(Optional min); + + /** Clears the value of min field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMin() { + return min(Optional.empty()); + } + + /** + * Setter for p5. + * + *

    p5: Output only. The 5th percentile of the values in the population. + */ + @JsonProperty("p5") + public abstract Builder p5(Double p5); + + @ExcludeFromGeneratedCoverageReport + abstract Builder p5(Optional p5); + + /** Clears the value of p5 field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearP5() { + return p5(Optional.empty()); + } + + /** + * Setter for p95. + * + *

    p95: Output only. The 95th percentile of the values in the population. + */ + @JsonProperty("p95") + public abstract Builder p95(Double p95); + + @ExcludeFromGeneratedCoverageReport + abstract Builder p95(Optional p95); + + /** Clears the value of p95 field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearP95() { + return p95(Optional.empty()); + } + + /** + * Setter for sum. + * + *

    sum: Output only. Sum of a given population of values. + */ + @JsonProperty("sum") + public abstract Builder sum(Double sum); + + @ExcludeFromGeneratedCoverageReport + abstract Builder sum(Optional sum); + + /** Clears the value of sum field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSum() { + return sum(Optional.empty()); + } + + public abstract DatasetDistribution build(); + } + + /** 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 new file mode 100644 index 00000000000..c4e278404a3 --- /dev/null +++ b/src/main/java/com/google/genai/types/DatasetDistributionDistributionBucket.java @@ -0,0 +1,131 @@ +/* + * 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; + +/** + * 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 { + /** Output only. Number of values in the bucket. */ + @JsonProperty("count") + public abstract Optional count(); + + /** Output only. Left bound of the bucket. */ + @JsonProperty("left") + public abstract Optional left(); + + /** Output only. Right bound of the bucket. */ + @JsonProperty("right") + public abstract Optional right(); + + /** Instantiates a builder for DatasetDistributionDistributionBucket. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DatasetDistributionDistributionBucket.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DatasetDistributionDistributionBucket. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `DatasetDistributionDistributionBucket.builder()` for + * instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_DatasetDistributionDistributionBucket.Builder(); + } + + /** + * Setter for count. + * + *

    count: Output only. Number of values in the bucket. + */ + @JsonProperty("count") + public abstract Builder count(Long count); + + @ExcludeFromGeneratedCoverageReport + abstract Builder count(Optional count); + + /** Clears the value of count field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCount() { + return count(Optional.empty()); + } + + /** + * Setter for left. + * + *

    left: Output only. Left bound of the bucket. + */ + @JsonProperty("left") + public abstract Builder left(Double left); + + @ExcludeFromGeneratedCoverageReport + abstract Builder left(Optional left); + + /** Clears the value of left field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLeft() { + return left(Optional.empty()); + } + + /** + * Setter for right. + * + *

    right: Output only. Right bound of the bucket. + */ + @JsonProperty("right") + public abstract Builder right(Double right); + + @ExcludeFromGeneratedCoverageReport + abstract Builder right(Optional right); + + /** Clears the value of right field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearRight() { + return right(Optional.empty()); + } + + public abstract DatasetDistributionDistributionBucket build(); + } + + /** 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 new file mode 100644 index 00000000000..2affb7e1f9f --- /dev/null +++ b/src/main/java/com/google/genai/types/DatasetStats.java @@ -0,0 +1,377 @@ +/* + * 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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** 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 { + /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */ + @JsonProperty("droppedExampleIndices") + public abstract Optional> droppedExampleIndices(); + + /** + * Output only. For each index in `dropped_example_indices`, the user-facing reason why the + * example was dropped. + */ + @JsonProperty("droppedExampleReasons") + public abstract Optional> droppedExampleReasons(); + + /** Output only. Number of billable characters in the tuning dataset. */ + @JsonProperty("totalBillableCharacterCount") + public abstract Optional totalBillableCharacterCount(); + + /** Output only. Number of tuning characters in the tuning dataset. */ + @JsonProperty("totalTuningCharacterCount") + public abstract Optional totalTuningCharacterCount(); + + /** 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 messages in the training dataset uri. */ + @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 messages per example. */ + @JsonProperty("userMessagePerExampleDistribution") + public abstract Optional userMessagePerExampleDistribution(); + + /** Output only. Dataset distributions for the user output tokens. */ + @JsonProperty("userOutputTokenDistribution") + public abstract Optional userOutputTokenDistribution(); + + /** Instantiates a builder for DatasetStats. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DatasetStats.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DatasetStats. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DatasetStats.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_DatasetStats.Builder(); + } + + /** + * Setter for droppedExampleIndices. + * + *

    droppedExampleIndices: Output only. A partial sample of the indices (starting from 1) of + * the dropped examples. + */ + @JsonProperty("droppedExampleIndices") + public abstract Builder droppedExampleIndices(List droppedExampleIndices); + + /** + * Setter for droppedExampleIndices. + * + *

    droppedExampleIndices: Output only. A partial sample of the indices (starting from 1) of + * the dropped examples. + */ + @CanIgnoreReturnValue + public Builder droppedExampleIndices(Long... droppedExampleIndices) { + return droppedExampleIndices(Arrays.asList(droppedExampleIndices)); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder droppedExampleIndices(Optional> droppedExampleIndices); + + /** Clears the value of droppedExampleIndices field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDroppedExampleIndices() { + return droppedExampleIndices(Optional.empty()); + } + + /** + * Setter for droppedExampleReasons. + * + *

    droppedExampleReasons: Output only. For each index in `dropped_example_indices`, the + * user-facing reason why the example was dropped. + */ + @JsonProperty("droppedExampleReasons") + public abstract Builder droppedExampleReasons(List droppedExampleReasons); + + /** + * Setter for droppedExampleReasons. + * + *

    droppedExampleReasons: Output only. For each index in `dropped_example_indices`, the + * user-facing reason why the example was dropped. + */ + @CanIgnoreReturnValue + public Builder droppedExampleReasons(String... droppedExampleReasons) { + return droppedExampleReasons(Arrays.asList(droppedExampleReasons)); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder droppedExampleReasons(Optional> droppedExampleReasons); + + /** Clears the value of droppedExampleReasons field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDroppedExampleReasons() { + return droppedExampleReasons(Optional.empty()); + } + + /** + * Setter for totalBillableCharacterCount. + * + *

    totalBillableCharacterCount: Output only. Number of billable characters in the tuning + * dataset. + */ + @JsonProperty("totalBillableCharacterCount") + public abstract Builder totalBillableCharacterCount(Long totalBillableCharacterCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder totalBillableCharacterCount(Optional totalBillableCharacterCount); + + /** Clears the value of totalBillableCharacterCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTotalBillableCharacterCount() { + return totalBillableCharacterCount(Optional.empty()); + } + + /** + * Setter for totalTuningCharacterCount. + * + *

    totalTuningCharacterCount: Output only. Number of tuning characters in the tuning dataset. + */ + @JsonProperty("totalTuningCharacterCount") + public abstract Builder totalTuningCharacterCount(Long totalTuningCharacterCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder totalTuningCharacterCount(Optional totalTuningCharacterCount); + + /** Clears the value of totalTuningCharacterCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTotalTuningCharacterCount() { + return totalTuningCharacterCount(Optional.empty()); + } + + /** + * Setter for tuningDatasetExampleCount. + * + *

    tuningDatasetExampleCount: Output only. Number of examples in the tuning dataset. + */ + @JsonProperty("tuningDatasetExampleCount") + public abstract Builder tuningDatasetExampleCount(Long tuningDatasetExampleCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder tuningDatasetExampleCount(Optional tuningDatasetExampleCount); + + /** Clears the value of tuningDatasetExampleCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTuningDatasetExampleCount() { + return tuningDatasetExampleCount(Optional.empty()); + } + + /** + * Setter for tuningStepCount. + * + *

    tuningStepCount: Output only. Number of tuning steps for this Tuning Job. + */ + @JsonProperty("tuningStepCount") + public abstract Builder tuningStepCount(Long tuningStepCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder tuningStepCount(Optional tuningStepCount); + + /** Clears the value of tuningStepCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTuningStepCount() { + return tuningStepCount(Optional.empty()); + } + + /** + * Setter for userDatasetExamples. + * + *

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

    userDatasetExamples: Output only. Sample user messages in the training dataset uri. + */ + @CanIgnoreReturnValue + public Builder userDatasetExamples(Content... userDatasetExamples) { + return userDatasetExamples(Arrays.asList(userDatasetExamples)); + } + + /** + * Setter for userDatasetExamples builder. + * + *

    userDatasetExamples: Output only. Sample user messages in the training dataset uri. + */ + @CanIgnoreReturnValue + public Builder userDatasetExamples(Content.Builder... userDatasetExamplesBuilders) { + return userDatasetExamples( + Arrays.asList(userDatasetExamplesBuilders).stream() + .map(Content.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder userDatasetExamples(Optional> userDatasetExamples); + + /** Clears the value of userDatasetExamples field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUserDatasetExamples() { + return userDatasetExamples(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder userInputTokenDistribution( + DatasetDistribution.Builder userInputTokenDistributionBuilder) { + return userInputTokenDistribution(userInputTokenDistributionBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder userInputTokenDistribution( + Optional userInputTokenDistribution); + + /** Clears the value of userInputTokenDistribution field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUserInputTokenDistribution() { + return userInputTokenDistribution(Optional.empty()); + } + + /** + * Setter for userMessagePerExampleDistribution. + * + *

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

    userMessagePerExampleDistribution: Output only. Dataset distributions for the messages per + * example. + */ + @CanIgnoreReturnValue + public Builder userMessagePerExampleDistribution( + DatasetDistribution.Builder userMessagePerExampleDistributionBuilder) { + return userMessagePerExampleDistribution(userMessagePerExampleDistributionBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder userMessagePerExampleDistribution( + Optional userMessagePerExampleDistribution); + + /** Clears the value of userMessagePerExampleDistribution field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUserMessagePerExampleDistribution() { + return userMessagePerExampleDistribution(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder userOutputTokenDistribution( + DatasetDistribution.Builder userOutputTokenDistributionBuilder) { + return userOutputTokenDistribution(userOutputTokenDistributionBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder userOutputTokenDistribution( + Optional userOutputTokenDistribution); + + /** Clears the value of userOutputTokenDistribution field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUserOutputTokenDistribution() { + return userOutputTokenDistribution(Optional.empty()); + } + + public abstract DatasetStats build(); + } + + /** 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 new file mode 100644 index 00000000000..e6ee9375d71 --- /dev/null +++ b/src/main/java/com/google/genai/types/DeleteBatchJobConfig.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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Optional parameters for models.get method. */ +@AutoValue +@JsonDeserialize(builder = DeleteBatchJobConfig.Builder.class) +public abstract class DeleteBatchJobConfig extends JsonSerializable { + /** Used to override HTTP request options. */ + @JsonProperty("httpOptions") + public abstract Optional httpOptions(); + + /** Instantiates a builder for DeleteBatchJobConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DeleteBatchJobConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DeleteBatchJobConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DeleteBatchJobConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_DeleteBatchJobConfig.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. + */ + @CanIgnoreReturnValue + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + + public abstract DeleteBatchJobConfig build(); + } + + /** 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 new file mode 100644 index 00000000000..925d2dfc6b7 --- /dev/null +++ b/src/main/java/com/google/genai/types/DeleteBatchJobParameters.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; + +/** Config for batches.delete parameters. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = DeleteBatchJobParameters.Builder.class) +public abstract class DeleteBatchJobParameters extends JsonSerializable { + /** + * A fully-qualified BatchJob resource name or ID. Example: + * "projects/.../locations/.../batchPredictionJobs/456" or "456" when project and location are + * initialized in the client. + */ + @JsonProperty("name") + public abstract Optional name(); + + /** Optional parameters for the request. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for DeleteBatchJobParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DeleteBatchJobParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DeleteBatchJobParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DeleteBatchJobParameters.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_DeleteBatchJobParameters.Builder(); + } + + /** + * Setter for name. + * + *

    name: A fully-qualified BatchJob resource name or ID. Example: + * "projects/.../locations/.../batchPredictionJobs/456" or "456" when project and location are + * initialized in the client. + */ + @JsonProperty("name") + public abstract Builder name(String name); + + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + + /** + * Setter for config. + * + *

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

    config: Optional parameters for the request. + */ + @CanIgnoreReturnValue + public Builder config(DeleteBatchJobConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + public abstract DeleteBatchJobParameters build(); + } + + /** 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..97bbea600bd 100644 --- a/src/main/java/com/google/genai/types/DeleteCachedContentConfig.java +++ b/src/main/java/com/google/genai/types/DeleteCachedContentConfig.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; @@ -34,6 +35,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(); } @@ -63,14 +65,26 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + public abstract DeleteCachedContentConfig build(); } /** 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..39058b16c8b 100644 --- a/src/main/java/com/google/genai/types/DeleteCachedContentParameters.java +++ b/src/main/java/com/google/genai/types/DeleteCachedContentParameters.java @@ -23,6 +23,7 @@ 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; @@ -40,6 +41,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(); } @@ -66,6 +68,16 @@ private static Builder create() { @JsonProperty("name") public abstract Builder name(String name); + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + /** * Setter for config. * @@ -79,14 +91,26 @@ private static Builder create() { * *

    config: Optional parameters for the request. */ + @CanIgnoreReturnValue public Builder config(DeleteCachedContentConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract DeleteCachedContentParameters build(); } /** 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..35c4d076dc2 100644 --- a/src/main/java/com/google/genai/types/DeleteCachedContentResponse.java +++ b/src/main/java/com/google/genai/types/DeleteCachedContentResponse.java @@ -19,15 +19,23 @@ 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; /** 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 +52,39 @@ 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. + */ + @CanIgnoreReturnValue + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + 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/DeleteDocumentConfig.java b/src/main/java/com/google/genai/types/DeleteDocumentConfig.java new file mode 100644 index 00000000000..306dd850675 --- /dev/null +++ b/src/main/java/com/google/genai/types/DeleteDocumentConfig.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.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; + +/** Config for optional parameters. */ +@AutoValue +@JsonDeserialize(builder = DeleteDocumentConfig.Builder.class) +public abstract class DeleteDocumentConfig extends JsonSerializable { + /** Used to override HTTP request options. */ + @JsonProperty("httpOptions") + public abstract Optional httpOptions(); + + /** If set to true, any `Chunk`s and objects related to this `Document` will also be deleted. */ + @JsonProperty("force") + public abstract Optional force(); + + /** Instantiates a builder for DeleteDocumentConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DeleteDocumentConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DeleteDocumentConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DeleteDocumentConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_DeleteDocumentConfig.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. + */ + @CanIgnoreReturnValue + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + + /** + * Setter for force. + * + *

    force: If set to true, any `Chunk`s and objects related to this `Document` will also be + * deleted. + */ + @JsonProperty("force") + public abstract Builder force(boolean force); + + @ExcludeFromGeneratedCoverageReport + abstract Builder force(Optional force); + + /** Clears the value of force field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearForce() { + return force(Optional.empty()); + } + + public abstract DeleteDocumentConfig build(); + } + + /** Deserializes a JSON string to a DeleteDocumentConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static DeleteDocumentConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, DeleteDocumentConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/DeleteDocumentParameters.java b/src/main/java/com/google/genai/types/DeleteDocumentParameters.java new file mode 100644 index 00000000000..b68736d6ea4 --- /dev/null +++ b/src/main/java/com/google/genai/types/DeleteDocumentParameters.java @@ -0,0 +1,119 @@ +/* + * 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; + +/** Config for documents.delete parameters. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = DeleteDocumentParameters.Builder.class) +public abstract class DeleteDocumentParameters extends JsonSerializable { + /** + * The resource name of the Document. Example: + * fileSearchStores/file-search-store-foo/documents/documents-bar + */ + @JsonProperty("name") + public abstract Optional name(); + + /** Optional parameters for the request. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for DeleteDocumentParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DeleteDocumentParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DeleteDocumentParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DeleteDocumentParameters.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_DeleteDocumentParameters.Builder(); + } + + /** + * Setter for name. + * + *

    name: The resource name of the Document. Example: + * fileSearchStores/file-search-store-foo/documents/documents-bar + */ + @JsonProperty("name") + public abstract Builder name(String name); + + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + + /** + * Setter for config. + * + *

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

    config: Optional parameters for the request. + */ + @CanIgnoreReturnValue + public Builder config(DeleteDocumentConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + public abstract DeleteDocumentParameters build(); + } + + /** Deserializes a JSON string to a DeleteDocumentParameters object. */ + @ExcludeFromGeneratedCoverageReport + public static DeleteDocumentParameters fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, DeleteDocumentParameters.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..f1d4df1ad48 100644 --- a/src/main/java/com/google/genai/types/DeleteFileConfig.java +++ b/src/main/java/com/google/genai/types/DeleteFileConfig.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; @@ -34,6 +35,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(); } @@ -63,14 +65,26 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + public abstract DeleteFileConfig build(); } /** 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..a4ab714f297 100644 --- a/src/main/java/com/google/genai/types/DeleteFileParameters.java +++ b/src/main/java/com/google/genai/types/DeleteFileParameters.java @@ -23,6 +23,7 @@ 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; @@ -40,6 +41,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(); } @@ -64,6 +66,16 @@ private static Builder create() { @JsonProperty("name") public abstract Builder name(String name); + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + /** * Setter for config. * @@ -77,14 +89,26 @@ private static Builder create() { * *

    config: Used to override the default configuration. */ + @CanIgnoreReturnValue public Builder config(DeleteFileConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract DeleteFileParameters build(); } /** 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..9fdf155a1f1 100644 --- a/src/main/java/com/google/genai/types/DeleteFileResponse.java +++ b/src/main/java/com/google/genai/types/DeleteFileResponse.java @@ -19,15 +19,23 @@ 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; /** 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 +52,39 @@ 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. + */ + @CanIgnoreReturnValue + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + 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/DeleteFileSearchStoreConfig.java b/src/main/java/com/google/genai/types/DeleteFileSearchStoreConfig.java new file mode 100644 index 00000000000..0ad4f6b73a7 --- /dev/null +++ b/src/main/java/com/google/genai/types/DeleteFileSearchStoreConfig.java @@ -0,0 +1,119 @@ +/* + * 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; + +/** Optional parameters for deleting a FileSearchStore. */ +@AutoValue +@JsonDeserialize(builder = DeleteFileSearchStoreConfig.Builder.class) +public abstract class DeleteFileSearchStoreConfig extends JsonSerializable { + /** Used to override HTTP request options. */ + @JsonProperty("httpOptions") + public abstract Optional httpOptions(); + + /** + * If set to true, any Documents and objects related to this FileSearchStore will also be deleted. + * If false (the default), a FAILED_PRECONDITION error will be returned if the FileSearchStore + * contains any Documents. + */ + @JsonProperty("force") + public abstract Optional force(); + + /** Instantiates a builder for DeleteFileSearchStoreConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DeleteFileSearchStoreConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DeleteFileSearchStoreConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DeleteFileSearchStoreConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_DeleteFileSearchStoreConfig.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. + */ + @CanIgnoreReturnValue + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + + /** + * Setter for force. + * + *

    force: If set to true, any Documents and objects related to this FileSearchStore will also + * be deleted. If false (the default), a FAILED_PRECONDITION error will be returned if the + * FileSearchStore contains any Documents. + */ + @JsonProperty("force") + public abstract Builder force(boolean force); + + @ExcludeFromGeneratedCoverageReport + abstract Builder force(Optional force); + + /** Clears the value of force field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearForce() { + return force(Optional.empty()); + } + + public abstract DeleteFileSearchStoreConfig build(); + } + + /** Deserializes a JSON string to a DeleteFileSearchStoreConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static DeleteFileSearchStoreConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, DeleteFileSearchStoreConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/DeleteFileSearchStoreParameters.java b/src/main/java/com/google/genai/types/DeleteFileSearchStoreParameters.java new file mode 100644 index 00000000000..e04ca3f4a66 --- /dev/null +++ b/src/main/java/com/google/genai/types/DeleteFileSearchStoreParameters.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.api.core.InternalApi; +import com.google.auto.value.AutoValue; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Config for file_search_stores.delete parameters. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = DeleteFileSearchStoreParameters.Builder.class) +public abstract class DeleteFileSearchStoreParameters extends JsonSerializable { + /** + * The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123` + */ + @JsonProperty("name") + public abstract Optional name(); + + /** Optional parameters for the request. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for DeleteFileSearchStoreParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DeleteFileSearchStoreParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DeleteFileSearchStoreParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `DeleteFileSearchStoreParameters.builder()` for instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_DeleteFileSearchStoreParameters.Builder(); + } + + /** + * Setter for name. + * + *

    name: The resource name of the FileSearchStore. Example: + * `fileSearchStores/my-file-search-store-123` + */ + @JsonProperty("name") + public abstract Builder name(String name); + + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + + /** + * Setter for config. + * + *

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

    config: Optional parameters for the request. + */ + @CanIgnoreReturnValue + public Builder config(DeleteFileSearchStoreConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + public abstract DeleteFileSearchStoreParameters build(); + } + + /** Deserializes a JSON string to a DeleteFileSearchStoreParameters object. */ + @ExcludeFromGeneratedCoverageReport + public static DeleteFileSearchStoreParameters fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, DeleteFileSearchStoreParameters.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..71dfb03674c 100644 --- a/src/main/java/com/google/genai/types/DeleteModelConfig.java +++ b/src/main/java/com/google/genai/types/DeleteModelConfig.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; @@ -34,6 +35,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(); } @@ -63,14 +65,26 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + public abstract DeleteModelConfig build(); } /** 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..82fa2ae2b8f 100644 --- a/src/main/java/com/google/genai/types/DeleteModelParameters.java +++ b/src/main/java/com/google/genai/types/DeleteModelParameters.java @@ -23,6 +23,7 @@ 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; @@ -40,6 +41,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(); } @@ -64,6 +66,16 @@ private static Builder create() { @JsonProperty("model") public abstract Builder model(String model); + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + /** * Setter for config. * @@ -77,14 +89,26 @@ private static Builder create() { * *

    config: Optional parameters for the request. */ + @CanIgnoreReturnValue public Builder config(DeleteModelConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract DeleteModelParameters build(); } /** 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..be2077b9026 100644 --- a/src/main/java/com/google/genai/types/DeleteModelResponse.java +++ b/src/main/java/com/google/genai/types/DeleteModelResponse.java @@ -19,15 +19,23 @@ 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; /** 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 +52,39 @@ 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. + */ + @CanIgnoreReturnValue + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + 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 new file mode 100644 index 00000000000..73f6cc6acf7 --- /dev/null +++ b/src/main/java/com/google/genai/types/DeleteResourceJob.java @@ -0,0 +1,167 @@ +/* + * 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; + +/** The return value of delete operation. */ +@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(); + + /** */ + @JsonProperty("done") + public abstract Optional done(); + + /** */ + @JsonProperty("error") + public abstract Optional error(); + + /** Instantiates a builder for DeleteResourceJob. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DeleteResourceJob.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DeleteResourceJob. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DeleteResourceJob.builder()` for instantiation. */ + @JsonCreator + 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. + */ + @CanIgnoreReturnValue + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + + /** + * Setter for name. + * + *

    name: + */ + @JsonProperty("name") + public abstract Builder name(String name); + + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + + /** + * Setter for done. + * + *

    done: + */ + @JsonProperty("done") + public abstract Builder done(boolean done); + + @ExcludeFromGeneratedCoverageReport + abstract Builder done(Optional done); + + /** Clears the value of done field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDone() { + return done(Optional.empty()); + } + + /** + * Setter for error. + * + *

    error: + */ + @JsonProperty("error") + public abstract Builder error(JobError error); + + /** + * Setter for error builder. + * + *

    error: + */ + @CanIgnoreReturnValue + public Builder error(JobError.Builder errorBuilder) { + return error(errorBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder error(Optional error); + + /** Clears the value of error field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearError() { + return error(Optional.empty()); + } + + public abstract DeleteResourceJob build(); + } + + /** 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 new file mode 100644 index 00000000000..719a491e653 --- /dev/null +++ b/src/main/java/com/google/genai/types/DistillationDataStats.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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** + * Statistics for distillation prompt dataset. These statistics do not include the responses sampled + * from the teacher model. This data type is not supported in Gemini API. + */ +@AutoValue +@JsonDeserialize(builder = DistillationDataStats.Builder.class) +public abstract class DistillationDataStats extends JsonSerializable { + /** Output only. Statistics computed for the training dataset. */ + @JsonProperty("trainingDatasetStats") + public abstract Optional trainingDatasetStats(); + + /** Instantiates a builder for DistillationDataStats. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DistillationDataStats.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DistillationDataStats. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DistillationDataStats.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_DistillationDataStats.Builder(); + } + + /** + * Setter for trainingDatasetStats. + * + *

    trainingDatasetStats: Output only. Statistics computed for the training dataset. + */ + @JsonProperty("trainingDatasetStats") + public abstract Builder trainingDatasetStats(DatasetStats trainingDatasetStats); + + /** + * Setter for trainingDatasetStats builder. + * + *

    trainingDatasetStats: Output only. Statistics computed for the training dataset. + */ + @CanIgnoreReturnValue + public Builder trainingDatasetStats(DatasetStats.Builder trainingDatasetStatsBuilder) { + return trainingDatasetStats(trainingDatasetStatsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder trainingDatasetStats(Optional trainingDatasetStats); + + /** Clears the value of trainingDatasetStats field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTrainingDatasetStats() { + return trainingDatasetStats(Optional.empty()); + } + + public abstract DistillationDataStats build(); + } + + /** 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/DistillationHyperParameters.java b/src/main/java/com/google/genai/types/DistillationHyperParameters.java new file mode 100644 index 00000000000..8275f6ad40b --- /dev/null +++ b/src/main/java/com/google/genai/types/DistillationHyperParameters.java @@ -0,0 +1,199 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 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 distillation. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = DistillationHyperParameters.Builder.class) +public abstract class DistillationHyperParameters extends JsonSerializable { + /** Optional. Adapter size for distillation. */ + @JsonProperty("adapterSize") + public abstract Optional adapterSize(); + + /** + * 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(); + + /** + * The batch size hyperparameter for tuning. This is only supported for OSS models in Gemini + * Enterprise Agent Platform. + */ + @JsonProperty("batchSize") + public abstract Optional batchSize(); + + /** The learning rate for tuning. OSS models only. */ + @JsonProperty("learningRate") + public abstract Optional learningRate(); + + /** Instantiates a builder for DistillationHyperParameters. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DistillationHyperParameters.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DistillationHyperParameters. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DistillationHyperParameters.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_DistillationHyperParameters.Builder(); + } + + /** + * Setter for adapterSize. + * + *

    adapterSize: Optional. Adapter size for distillation. + */ + @JsonProperty("adapterSize") + public abstract Builder adapterSize(AdapterSize adapterSize); + + @ExcludeFromGeneratedCoverageReport + abstract Builder adapterSize(Optional adapterSize); + + /** Clears the value of adapterSize field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAdapterSize() { + return adapterSize(Optional.empty()); + } + + /** + * Setter for adapterSize given a known enum. + * + *

    adapterSize: Optional. Adapter size for distillation. + */ + @CanIgnoreReturnValue + public Builder adapterSize(AdapterSize.Known knownType) { + return adapterSize(new AdapterSize(knownType)); + } + + /** + * Setter for adapterSize given a string. + * + *

    adapterSize: Optional. Adapter size for distillation. + */ + @CanIgnoreReturnValue + public Builder adapterSize(String adapterSize) { + return adapterSize(new AdapterSize(adapterSize)); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder epochCount(Optional epochCount); + + /** Clears the value of epochCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEpochCount() { + return epochCount(Optional.empty()); + } + + /** + * Setter for learningRateMultiplier. + * + *

    learningRateMultiplier: Optional. Multiplier for adjusting the default learning rate. + */ + @JsonProperty("learningRateMultiplier") + public abstract Builder learningRateMultiplier(Double learningRateMultiplier); + + @ExcludeFromGeneratedCoverageReport + abstract Builder learningRateMultiplier(Optional learningRateMultiplier); + + /** Clears the value of learningRateMultiplier field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLearningRateMultiplier() { + return learningRateMultiplier(Optional.empty()); + } + + /** + * Setter for batchSize. + * + *

    batchSize: The batch size hyperparameter for tuning. This is only supported for OSS models + * in Gemini Enterprise Agent Platform. + */ + @JsonProperty("batchSize") + public abstract Builder batchSize(Integer batchSize); + + @ExcludeFromGeneratedCoverageReport + abstract Builder batchSize(Optional batchSize); + + /** Clears the value of batchSize field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBatchSize() { + return batchSize(Optional.empty()); + } + + /** + * Setter for learningRate. + * + *

    learningRate: The learning rate for tuning. OSS models only. + */ + @JsonProperty("learningRate") + public abstract Builder learningRate(Float learningRate); + + @ExcludeFromGeneratedCoverageReport + abstract Builder learningRate(Optional learningRate); + + /** Clears the value of learningRate field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLearningRate() { + return learningRate(Optional.empty()); + } + + public abstract DistillationHyperParameters build(); + } + + /** Deserializes a JSON string to a DistillationHyperParameters object. */ + @ExcludeFromGeneratedCoverageReport + public static DistillationHyperParameters fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, DistillationHyperParameters.class); + } +} diff --git a/src/main/java/com/google/genai/types/DistillationSamplingSpec.java b/src/main/java/com/google/genai/types/DistillationSamplingSpec.java new file mode 100644 index 00000000000..94ec3ceaa84 --- /dev/null +++ b/src/main/java/com/google/genai/types/DistillationSamplingSpec.java @@ -0,0 +1,140 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 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; + +/** + * Spec for creating a distilled dataset in Vertex Dataset. This data type is not supported in + * Gemini API. + */ +@AutoValue +@JsonDeserialize(builder = DistillationSamplingSpec.Builder.class) +public abstract class DistillationSamplingSpec extends JsonSerializable { + /** + * Optional. 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. 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 distillation. The + * dataset must be formatted as a JSONL file. + */ + @JsonProperty("validationDatasetUri") + public abstract Optional validationDatasetUri(); + + /** Instantiates a builder for DistillationSamplingSpec. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DistillationSamplingSpec.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DistillationSamplingSpec. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DistillationSamplingSpec.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_DistillationSamplingSpec.Builder(); + } + + /** + * Setter for baseTeacherModel. + * + *

    baseTeacherModel: Optional. 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder baseTeacherModel(Optional baseTeacherModel); + + /** Clears the value of baseTeacherModel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBaseTeacherModel() { + return baseTeacherModel(Optional.empty()); + } + + /** + * Setter for tunedTeacherModelSource. + * + *

    tunedTeacherModelSource: Optional. The resource name of the Tuned teacher model. Format: + * `projects/{project}/locations/{location}/models/{model}`. + */ + @JsonProperty("tunedTeacherModelSource") + public abstract Builder tunedTeacherModelSource(String tunedTeacherModelSource); + + @ExcludeFromGeneratedCoverageReport + abstract Builder tunedTeacherModelSource(Optional tunedTeacherModelSource); + + /** Clears the value of tunedTeacherModelSource field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTunedTeacherModelSource() { + return tunedTeacherModelSource(Optional.empty()); + } + + /** + * Setter for validationDatasetUri. + * + *

    validationDatasetUri: Optional. Cloud Storage path to file containing validation dataset + * for distillation. The dataset must be formatted as a JSONL file. + */ + @JsonProperty("validationDatasetUri") + public abstract Builder validationDatasetUri(String validationDatasetUri); + + @ExcludeFromGeneratedCoverageReport + abstract Builder validationDatasetUri(Optional validationDatasetUri); + + /** Clears the value of validationDatasetUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearValidationDatasetUri() { + return validationDatasetUri(Optional.empty()); + } + + public abstract DistillationSamplingSpec build(); + } + + /** Deserializes a JSON string to a DistillationSamplingSpec object. */ + @ExcludeFromGeneratedCoverageReport + public static DistillationSamplingSpec fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, DistillationSamplingSpec.class); + } +} diff --git a/src/main/java/com/google/genai/types/DistillationSpec.java b/src/main/java/com/google/genai/types/DistillationSpec.java new file mode 100644 index 00000000000..d4780ab5170 --- /dev/null +++ b/src/main/java/com/google/genai/types/DistillationSpec.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. + */ + +// 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; + +/** Distillation tuning spec for tuning. */ +@AutoValue +@JsonDeserialize(builder = DistillationSpec.Builder.class) +public abstract class DistillationSpec extends JsonSerializable { + /** The GCS URI of the prompt dataset to use during distillation. */ + @JsonProperty("promptDatasetUri") + public abstract Optional promptDatasetUri(); + + /** + * 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(); + + /** Tuning mode for tuning. */ + @JsonProperty("tuningMode") + public abstract Optional tuningMode(); + + /** Instantiates a builder for DistillationSpec. */ + @ExcludeFromGeneratedCoverageReport + 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 promptDatasetUri. + * + *

    promptDatasetUri: The GCS URI of the prompt dataset to use during distillation. + */ + @JsonProperty("promptDatasetUri") + public abstract Builder promptDatasetUri(String promptDatasetUri); + + @ExcludeFromGeneratedCoverageReport + abstract Builder promptDatasetUri(Optional promptDatasetUri); + + /** Clears the value of promptDatasetUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPromptDatasetUri() { + return promptDatasetUri(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder baseTeacherModel(Optional baseTeacherModel); + + /** Clears the value of baseTeacherModel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBaseTeacherModel() { + return baseTeacherModel(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder hyperParameters(DistillationHyperParameters.Builder hyperParametersBuilder) { + return hyperParameters(hyperParametersBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder hyperParameters(Optional hyperParameters); + + /** Clears the value of hyperParameters field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHyperParameters() { + return hyperParameters(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder pipelineRootDirectory(Optional pipelineRootDirectory); + + /** Clears the value of pipelineRootDirectory field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPipelineRootDirectory() { + return pipelineRootDirectory(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder studentModel(Optional studentModel); + + /** Clears the value of studentModel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearStudentModel() { + return studentModel(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder trainingDatasetUri(Optional trainingDatasetUri); + + /** Clears the value of trainingDatasetUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTrainingDatasetUri() { + return trainingDatasetUri(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder tunedTeacherModelSource(Optional tunedTeacherModelSource); + + /** Clears the value of tunedTeacherModelSource field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTunedTeacherModelSource() { + return tunedTeacherModelSource(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder validationDatasetUri(Optional validationDatasetUri); + + /** Clears the value of validationDatasetUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearValidationDatasetUri() { + return validationDatasetUri(Optional.empty()); + } + + /** + * Setter for tuningMode. + * + *

    tuningMode: Tuning mode for tuning. + */ + @JsonProperty("tuningMode") + public abstract Builder tuningMode(TuningMode tuningMode); + + @ExcludeFromGeneratedCoverageReport + abstract Builder tuningMode(Optional tuningMode); + + /** Clears the value of tuningMode field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTuningMode() { + return tuningMode(Optional.empty()); + } + + /** + * Setter for tuningMode given a known enum. + * + *

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

    tuningMode: Tuning mode for tuning. + */ + @CanIgnoreReturnValue + public Builder tuningMode(String tuningMode) { + return tuningMode(new TuningMode(tuningMode)); + } + + public abstract DistillationSpec build(); + } + + /** Deserializes a JSON string to a DistillationSpec object. */ + @ExcludeFromGeneratedCoverageReport + public static DistillationSpec fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, DistillationSpec.class); + } +} diff --git a/src/main/java/com/google/genai/types/Document.java b/src/main/java/com/google/genai/types/Document.java new file mode 100644 index 00000000000..0f309fb657b --- /dev/null +++ b/src/main/java/com/google/genai/types/Document.java @@ -0,0 +1,306 @@ +/* + * 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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.time.Instant; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** A Document is a collection of Chunks. */ +@AutoValue +@JsonDeserialize(builder = Document.Builder.class) +public abstract class Document extends JsonSerializable { + /** + * Immutable. Identifier. The `Document` resource name. The ID (name excluding the + * "fileSearchStores/*/documents/" prefix) can contain up to 40 characters that are lowercase + * alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on + * create, a unique name will be derived from `display_name` along with a 12 character random + * suffix. Example: + * `fileSearchStores/{file_search_store_id}/documents/my-awesome-doc-123a456b789c` + */ + @JsonProperty("name") + public abstract Optional name(); + + /** + * Optional. The human-readable display name for the `Document`. The display name must be no more + * than 512 characters in length, including spaces. Example: "Semantic Retriever Documentation". + */ + @JsonProperty("displayName") + public abstract Optional displayName(); + + /** Output only. Current state of the `Document`. */ + @JsonProperty("state") + public abstract Optional state(); + + /** Output only. The size of raw bytes ingested into the Document. */ + @JsonProperty("sizeBytes") + public abstract Optional sizeBytes(); + + /** Output only. The mime type of the Document. */ + @JsonProperty("mimeType") + public abstract Optional mimeType(); + + /** Output only. The Timestamp of when the `Document` was created. */ + @JsonProperty("createTime") + public abstract Optional createTime(); + + /** + * Optional. User provided custom metadata stored as key-value pairs used for querying. A + * `Document` can have a maximum of 20 `CustomMetadata`. + */ + @JsonProperty("customMetadata") + public abstract Optional> customMetadata(); + + /** Output only. The Timestamp of when the `Document` was last updated. */ + @JsonProperty("updateTime") + public abstract Optional updateTime(); + + /** Instantiates a builder for Document. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_Document.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for Document. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `Document.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_Document.Builder(); + } + + /** + * Setter for name. + * + *

    name: Immutable. Identifier. The `Document` resource name. The ID (name excluding the + * "fileSearchStores/*/documents/" prefix) can contain up to 40 characters that are + * lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is + * empty on create, a unique name will be derived from `display_name` along with a 12 character + * random suffix. Example: + * `fileSearchStores/{file_search_store_id}/documents/my-awesome-doc-123a456b789c` + */ + @JsonProperty("name") + public abstract Builder name(String name); + + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + + /** + * Setter for displayName. + * + *

    displayName: Optional. The human-readable display name for the `Document`. The display + * name must be no more than 512 characters in length, including spaces. Example: "Semantic + * Retriever Documentation". + */ + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + + /** + * Setter for state. + * + *

    state: Output only. Current state of the `Document`. + */ + @JsonProperty("state") + public abstract Builder state(DocumentState state); + + @ExcludeFromGeneratedCoverageReport + abstract Builder state(Optional state); + + /** Clears the value of state field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearState() { + return state(Optional.empty()); + } + + /** + * Setter for state given a known enum. + * + *

    state: Output only. Current state of the `Document`. + */ + @CanIgnoreReturnValue + public Builder state(DocumentState.Known knownType) { + return state(new DocumentState(knownType)); + } + + /** + * Setter for state given a string. + * + *

    state: Output only. Current state of the `Document`. + */ + @CanIgnoreReturnValue + public Builder state(String state) { + return state(new DocumentState(state)); + } + + /** + * Setter for sizeBytes. + * + *

    sizeBytes: Output only. The size of raw bytes ingested into the Document. + */ + @JsonProperty("sizeBytes") + public abstract Builder sizeBytes(Long sizeBytes); + + @ExcludeFromGeneratedCoverageReport + abstract Builder sizeBytes(Optional sizeBytes); + + /** Clears the value of sizeBytes field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSizeBytes() { + return sizeBytes(Optional.empty()); + } + + /** + * Setter for mimeType. + * + *

    mimeType: Output only. The mime type of the Document. + */ + @JsonProperty("mimeType") + public abstract Builder mimeType(String mimeType); + + @ExcludeFromGeneratedCoverageReport + abstract Builder mimeType(Optional mimeType); + + /** Clears the value of mimeType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMimeType() { + return mimeType(Optional.empty()); + } + + /** + * Setter for createTime. + * + *

    createTime: Output only. The Timestamp of when the `Document` was created. + */ + @JsonProperty("createTime") + public abstract Builder createTime(Instant createTime); + + @ExcludeFromGeneratedCoverageReport + abstract Builder createTime(Optional createTime); + + /** Clears the value of createTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCreateTime() { + return createTime(Optional.empty()); + } + + /** + * Setter for customMetadata. + * + *

    customMetadata: Optional. User provided custom metadata stored as key-value pairs used for + * querying. A `Document` can have a maximum of 20 `CustomMetadata`. + */ + @JsonProperty("customMetadata") + public abstract Builder customMetadata(List customMetadata); + + /** + * Setter for customMetadata. + * + *

    customMetadata: Optional. User provided custom metadata stored as key-value pairs used for + * querying. A `Document` can have a maximum of 20 `CustomMetadata`. + */ + @CanIgnoreReturnValue + public Builder customMetadata(CustomMetadata... customMetadata) { + return customMetadata(Arrays.asList(customMetadata)); + } + + /** + * Setter for customMetadata builder. + * + *

    customMetadata: Optional. User provided custom metadata stored as key-value pairs used for + * querying. A `Document` can have a maximum of 20 `CustomMetadata`. + */ + @CanIgnoreReturnValue + public Builder customMetadata(CustomMetadata.Builder... customMetadataBuilders) { + return customMetadata( + Arrays.asList(customMetadataBuilders).stream() + .map(CustomMetadata.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder customMetadata(Optional> customMetadata); + + /** Clears the value of customMetadata field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCustomMetadata() { + return customMetadata(Optional.empty()); + } + + /** + * Setter for updateTime. + * + *

    updateTime: Output only. The Timestamp of when the `Document` was last updated. + */ + @JsonProperty("updateTime") + public abstract Builder updateTime(Instant updateTime); + + @ExcludeFromGeneratedCoverageReport + abstract Builder updateTime(Optional updateTime); + + /** Clears the value of updateTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUpdateTime() { + return updateTime(Optional.empty()); + } + + public abstract Document build(); + } + + /** Deserializes a JSON string to a Document object. */ + @ExcludeFromGeneratedCoverageReport + public static Document fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, Document.class); + } +} diff --git a/src/main/java/com/google/genai/types/DocumentState.java b/src/main/java/com/google/genai/types/DocumentState.java new file mode 100644 index 00000000000..4cfaa658d77 --- /dev/null +++ b/src/main/java/com/google/genai/types/DocumentState.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 com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.google.common.base.Ascii; +import java.util.Objects; + +/** Output only. Current state of the `Document`. This enum is not supported in Vertex AI. */ +public class DocumentState { + + /** Enum representing the known values for DocumentState. */ + public enum Known { + /** The default value. This value is used if the state is omitted. */ + STATE_UNSPECIFIED, + + /** Some `Chunks` of the `Document` are being processed (embedding and vector storage). */ + STATE_PENDING, + + /** All `Chunks` of the `Document` is processed and available for querying. */ + STATE_ACTIVE, + + /** Some `Chunks` of the `Document` failed processing. */ + STATE_FAILED, + + DOCUMENT_STATE_UNSPECIFIED + } + + private Known documentStateEnum; + private final String value; + + @JsonCreator + public DocumentState(String value) { + this.value = value; + for (Known documentStateEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(documentStateEnum.toString(), value)) { + this.documentStateEnum = documentStateEnum; + break; + } + } + if (this.documentStateEnum == null) { + this.documentStateEnum = Known.DOCUMENT_STATE_UNSPECIFIED; + } + } + + public DocumentState(Known knownValue) { + this.documentStateEnum = 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 DocumentState)) { + return false; + } + + DocumentState other = (DocumentState) o; + + if (this.documentStateEnum != Known.DOCUMENT_STATE_UNSPECIFIED + && other.documentStateEnum != Known.DOCUMENT_STATE_UNSPECIFIED) { + return this.documentStateEnum == other.documentStateEnum; + } else if (this.documentStateEnum == Known.DOCUMENT_STATE_UNSPECIFIED + && other.documentStateEnum == Known.DOCUMENT_STATE_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.documentStateEnum != Known.DOCUMENT_STATE_UNSPECIFIED) { + return this.documentStateEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.documentStateEnum; + } +} diff --git a/src/main/java/com/google/genai/types/DownloadFileConfig.java b/src/main/java/com/google/genai/types/DownloadFileConfig.java index ec8e6aa6ccd..c73a6e69b71 100644 --- a/src/main/java/com/google/genai/types/DownloadFileConfig.java +++ b/src/main/java/com/google/genai/types/DownloadFileConfig.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; @@ -34,6 +35,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(); } @@ -63,14 +65,26 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + public abstract DownloadFileConfig build(); } /** 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/DownloadMediaConfig.java b/src/main/java/com/google/genai/types/DownloadMediaConfig.java new file mode 100644 index 00000000000..5b1a7abb52e --- /dev/null +++ b/src/main/java/com/google/genai/types/DownloadMediaConfig.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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** Used to override the default configuration. */ +@AutoValue +@JsonDeserialize(builder = DownloadMediaConfig.Builder.class) +public abstract class DownloadMediaConfig extends JsonSerializable { + /** Used to override HTTP request options. */ + @JsonProperty("httpOptions") + public abstract Optional httpOptions(); + + /** Instantiates a builder for DownloadMediaConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_DownloadMediaConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for DownloadMediaConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `DownloadMediaConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_DownloadMediaConfig.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. + */ + @CanIgnoreReturnValue + public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { + return httpOptions(httpOptionsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + + public abstract DownloadMediaConfig build(); + } + + /** Deserializes a JSON string to a DownloadMediaConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static DownloadMediaConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, DownloadMediaConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/DynamicRetrievalConfig.java b/src/main/java/com/google/genai/types/DynamicRetrievalConfig.java index d30de309374..f8a2953a540 100644 --- a/src/main/java/com/google/genai/types/DynamicRetrievalConfig.java +++ b/src/main/java/com/google/genai/types/DynamicRetrievalConfig.java @@ -30,10 +30,6 @@ @AutoValue @JsonDeserialize(builder = DynamicRetrievalConfig.Builder.class) public abstract class DynamicRetrievalConfig extends JsonSerializable { - /** The mode of the predictor to be used in dynamic retrieval. */ - @JsonProperty("mode") - public abstract Optional mode(); - /** * Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is * used. @@ -41,7 +37,12 @@ public abstract class DynamicRetrievalConfig extends JsonSerializable { @JsonProperty("dynamicThreshold") public abstract Optional dynamicThreshold(); + /** The mode of the predictor to be used in dynamic retrieval. */ + @JsonProperty("mode") + public abstract Optional mode(); + /** Instantiates a builder for DynamicRetrievalConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_DynamicRetrievalConfig.Builder(); } @@ -58,6 +59,25 @@ private static Builder create() { return new AutoValue_DynamicRetrievalConfig.Builder(); } + /** + * Setter for dynamicThreshold. + * + *

    dynamicThreshold: Optional. The threshold to be used in dynamic retrieval. If not set, a + * system default value is used. + */ + @JsonProperty("dynamicThreshold") + public abstract Builder dynamicThreshold(Float dynamicThreshold); + + @ExcludeFromGeneratedCoverageReport + abstract Builder dynamicThreshold(Optional dynamicThreshold); + + /** Clears the value of dynamicThreshold field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDynamicThreshold() { + return dynamicThreshold(Optional.empty()); + } + /** * Setter for mode. * @@ -66,29 +86,41 @@ private static Builder create() { @JsonProperty("mode") public abstract Builder mode(DynamicRetrievalConfigMode mode); + @ExcludeFromGeneratedCoverageReport + abstract Builder mode(Optional mode); + + /** Clears the value of mode field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMode() { + return mode(Optional.empty()); + } + + /** + * Setter for mode given a known enum. + * + *

    mode: The mode of the predictor to be used in dynamic retrieval. + */ @CanIgnoreReturnValue public Builder mode(DynamicRetrievalConfigMode.Known knownType) { return mode(new DynamicRetrievalConfigMode(knownType)); } + /** + * Setter for mode given a string. + * + *

    mode: The mode of the predictor to be used in dynamic retrieval. + */ @CanIgnoreReturnValue public Builder mode(String mode) { return mode(new DynamicRetrievalConfigMode(mode)); } - /** - * Setter for dynamicThreshold. - * - *

    dynamicThreshold: Optional. The threshold to be used in dynamic retrieval. If not set, a - * system default value is used. - */ - - @JsonProperty("dynamicThreshold") - public abstract Builder dynamicThreshold(Float dynamicThreshold); public abstract DynamicRetrievalConfig build(); } /** 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..5d52901d9e8 100644 --- a/src/main/java/com/google/genai/types/DynamicRetrievalConfigMode.java +++ b/src/main/java/com/google/genai/types/DynamicRetrievalConfigMode.java @@ -23,7 +23,7 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Config for the dynamic retrieval config mode. */ +/** The mode of the predictor to be used in dynamic retrieval. */ public class DynamicRetrievalConfigMode { /** Enum representing the known values for DynamicRetrievalConfigMode. */ @@ -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 223b3084f4c..df850235ed3 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. */ @@ -46,7 +47,10 @@ public abstract class EditImageConfig extends JsonSerializable { @JsonProperty("numberOfImages") public abstract Optional numberOfImages(); - /** Aspect ratio of the generated images. */ + /** + * Aspect ratio of the generated images. Supported values are "1:1", "3:4", "4:3", "9:16", and + * "16:9". + */ @JsonProperty("aspectRatio") public abstract Optional aspectRatio(); @@ -97,6 +101,14 @@ public abstract class EditImageConfig extends JsonSerializable { @JsonProperty("outputCompressionQuality") public abstract Optional outputCompressionQuality(); + /** Whether to add a watermark to the generated images. */ + @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(); @@ -109,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(); } @@ -138,10 +151,21 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + /** * Setter for outputGcsUri. * @@ -150,6 +174,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("outputGcsUri") public abstract Builder outputGcsUri(String outputGcsUri); + @ExcludeFromGeneratedCoverageReport + abstract Builder outputGcsUri(Optional outputGcsUri); + + /** Clears the value of outputGcsUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputGcsUri() { + return outputGcsUri(Optional.empty()); + } + /** * Setter for negativePrompt. * @@ -158,6 +192,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("negativePrompt") public abstract Builder negativePrompt(String negativePrompt); + @ExcludeFromGeneratedCoverageReport + abstract Builder negativePrompt(Optional negativePrompt); + + /** Clears the value of negativePrompt field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearNegativePrompt() { + return negativePrompt(Optional.empty()); + } + /** * Setter for numberOfImages. * @@ -166,14 +210,35 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("numberOfImages") public abstract Builder numberOfImages(Integer numberOfImages); + @ExcludeFromGeneratedCoverageReport + abstract Builder numberOfImages(Optional numberOfImages); + + /** Clears the value of numberOfImages field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearNumberOfImages() { + return numberOfImages(Optional.empty()); + } + /** * Setter for aspectRatio. * - *

    aspectRatio: Aspect ratio of the generated images. + *

    aspectRatio: Aspect ratio of the generated images. Supported values are "1:1", "3:4", + * "4:3", "9:16", and "16:9". */ @JsonProperty("aspectRatio") public abstract Builder aspectRatio(String aspectRatio); + @ExcludeFromGeneratedCoverageReport + abstract Builder aspectRatio(Optional aspectRatio); + + /** Clears the value of aspectRatio field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAspectRatio() { + return aspectRatio(Optional.empty()); + } + /** * Setter for guidanceScale. * @@ -183,6 +248,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("guidanceScale") public abstract Builder guidanceScale(Float guidanceScale); + @ExcludeFromGeneratedCoverageReport + abstract Builder guidanceScale(Optional guidanceScale); + + /** Clears the value of guidanceScale field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGuidanceScale() { + return guidanceScale(Optional.empty()); + } + /** * Setter for seed. * @@ -192,6 +267,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("seed") public abstract Builder seed(Integer seed); + @ExcludeFromGeneratedCoverageReport + abstract Builder seed(Optional seed); + + /** Clears the value of seed field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSeed() { + return seed(Optional.empty()); + } + /** * Setter for safetyFilterLevel. * @@ -200,43 +285,93 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("safetyFilterLevel") public abstract Builder safetyFilterLevel(SafetyFilterLevel safetyFilterLevel); + @ExcludeFromGeneratedCoverageReport + abstract Builder safetyFilterLevel(Optional safetyFilterLevel); + + /** Clears the value of safetyFilterLevel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSafetyFilterLevel() { + return safetyFilterLevel(Optional.empty()); + } + + /** + * 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder personGeneration(Optional personGeneration); + + /** Clears the value of personGeneration field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPersonGeneration() { + return personGeneration(Optional.empty()); + } + + /** + * 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 includeSafetyAttributes. * *

    includeSafetyAttributes: Whether to report the safety scores of each generated image and * the positive prompt in the response. */ - @JsonProperty("includeSafetyAttributes") public abstract Builder includeSafetyAttributes(boolean includeSafetyAttributes); + @ExcludeFromGeneratedCoverageReport + abstract Builder includeSafetyAttributes(Optional includeSafetyAttributes); + + /** Clears the value of includeSafetyAttributes field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearIncludeSafetyAttributes() { + return includeSafetyAttributes(Optional.empty()); + } + /** * Setter for includeRaiReason. * @@ -246,6 +381,16 @@ public Builder personGeneration(String personGeneration) { @JsonProperty("includeRaiReason") public abstract Builder includeRaiReason(boolean includeRaiReason); + @ExcludeFromGeneratedCoverageReport + abstract Builder includeRaiReason(Optional includeRaiReason); + + /** Clears the value of includeRaiReason field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearIncludeRaiReason() { + return includeRaiReason(Optional.empty()); + } + /** * Setter for language. * @@ -254,24 +399,54 @@ public Builder personGeneration(String personGeneration) { @JsonProperty("language") public abstract Builder language(ImagePromptLanguage language); + @ExcludeFromGeneratedCoverageReport + abstract Builder language(Optional language); + + /** Clears the value of language field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLanguage() { + return language(Optional.empty()); + } + + /** + * Setter for language given a known enum. + * + *

    language: Language of the text in the prompt. + */ @CanIgnoreReturnValue public Builder language(ImagePromptLanguage.Known knownType) { return language(new ImagePromptLanguage(knownType)); } + /** + * Setter for language given a string. + * + *

    language: Language of the text in the prompt. + */ @CanIgnoreReturnValue public Builder language(String language) { return language(new ImagePromptLanguage(language)); } + /** * Setter for outputMimeType. * *

    outputMimeType: MIME type of the generated image. */ - @JsonProperty("outputMimeType") public abstract Builder outputMimeType(String outputMimeType); + @ExcludeFromGeneratedCoverageReport + abstract Builder outputMimeType(Optional outputMimeType); + + /** Clears the value of outputMimeType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputMimeType() { + return outputMimeType(Optional.empty()); + } + /** * Setter for outputCompressionQuality. * @@ -281,6 +456,52 @@ public Builder language(String language) { @JsonProperty("outputCompressionQuality") public abstract Builder outputCompressionQuality(Integer outputCompressionQuality); + @ExcludeFromGeneratedCoverageReport + abstract Builder outputCompressionQuality(Optional outputCompressionQuality); + + /** Clears the value of outputCompressionQuality field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputCompressionQuality() { + return outputCompressionQuality(Optional.empty()); + } + + /** + * Setter for addWatermark. + * + *

    addWatermark: Whether to add a watermark to the generated images. + */ + @JsonProperty("addWatermark") + public abstract Builder addWatermark(boolean addWatermark); + + @ExcludeFromGeneratedCoverageReport + abstract Builder addWatermark(Optional addWatermark); + + /** Clears the value of addWatermark field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAddWatermark() { + return addWatermark(Optional.empty()); + } + + /** + * Setter for labels. + * + *

    labels: User specified labels to track billing usage. + */ + @JsonProperty("labels") + public abstract Builder labels(Map labels); + + @ExcludeFromGeneratedCoverageReport + abstract Builder labels(Optional> labels); + + /** Clears the value of labels field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLabels() { + return labels(Optional.empty()); + } + /** * Setter for editMode. * @@ -289,29 +510,60 @@ public Builder language(String language) { @JsonProperty("editMode") public abstract Builder editMode(EditMode editMode); + @ExcludeFromGeneratedCoverageReport + abstract Builder editMode(Optional editMode); + + /** Clears the value of editMode field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEditMode() { + return editMode(Optional.empty()); + } + + /** + * Setter for editMode given a known enum. + * + *

    editMode: Describes the editing mode for the request. + */ @CanIgnoreReturnValue public Builder editMode(EditMode.Known knownType) { return editMode(new EditMode(knownType)); } + /** + * Setter for editMode given a string. + * + *

    editMode: Describes the editing mode for the request. + */ @CanIgnoreReturnValue public Builder editMode(String editMode) { return editMode(new EditMode(editMode)); } + /** * 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder baseSteps(Optional baseSteps); + + /** Clears the value of baseSteps field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBaseSteps() { + return baseSteps(Optional.empty()); + } + public abstract EditImageConfig build(); } /** 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..c9a5c79353d 100644 --- a/src/main/java/com/google/genai/types/EditImageParameters.java +++ b/src/main/java/com/google/genai/types/EditImageParameters.java @@ -23,6 +23,7 @@ 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.Arrays; import java.util.List; @@ -41,7 +42,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 +51,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(); } @@ -74,6 +76,16 @@ private static Builder create() { @JsonProperty("model") public abstract Builder model(String model); + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + /** * Setter for prompt. * @@ -82,10 +94,20 @@ private static Builder create() { @JsonProperty("prompt") public abstract Builder prompt(String prompt); + @ExcludeFromGeneratedCoverageReport + abstract Builder prompt(Optional prompt); + + /** Clears the value of prompt field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPrompt() { + return prompt(Optional.empty()); + } + /** * 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,12 +115,23 @@ private static Builder create() { /** * Setter for referenceImages. * - *

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

    referenceImages: The reference images for editing. */ + @CanIgnoreReturnValue public Builder referenceImages(ReferenceImageAPI... referenceImages) { return referenceImages(Arrays.asList(referenceImages)); } + @ExcludeFromGeneratedCoverageReport + abstract Builder referenceImages(Optional> referenceImages); + + /** Clears the value of referenceImages field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearReferenceImages() { + return referenceImages(Optional.empty()); + } + /** * Setter for config. * @@ -112,14 +145,26 @@ public Builder referenceImages(ReferenceImageAPI... referenceImages) { * *

    config: Configuration for editing. */ + @CanIgnoreReturnValue public Builder config(EditImageConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract EditImageParameters build(); } /** 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..3c7671c0968 100644 --- a/src/main/java/com/google/genai/types/EditImageResponse.java +++ b/src/main/java/com/google/genai/types/EditImageResponse.java @@ -24,6 +24,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.Arrays; import java.util.List; @@ -33,11 +34,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 +60,34 @@ 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. + */ + @CanIgnoreReturnValue + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + /** * Setter for generatedImages. * @@ -67,6 +101,7 @@ private static Builder create() { * *

    generatedImages: Generated images. */ + @CanIgnoreReturnValue public Builder generatedImages(GeneratedImage... generatedImages) { return generatedImages(Arrays.asList(generatedImages)); } @@ -76,6 +111,7 @@ public Builder generatedImages(GeneratedImage... generatedImages) { * *

    generatedImages: Generated images. */ + @CanIgnoreReturnValue public Builder generatedImages(GeneratedImage.Builder... generatedImagesBuilders) { return generatedImages( Arrays.asList(generatedImagesBuilders).stream() @@ -83,10 +119,21 @@ public Builder generatedImages(GeneratedImage.Builder... generatedImagesBuilders .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder generatedImages(Optional> generatedImages); + + /** Clears the value of generatedImages field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGeneratedImages() { + return generatedImages(Optional.empty()); + } + public abstract EditImageResponse build(); } /** 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..191b16c1637 --- /dev/null +++ b/src/main/java/com/google/genai/types/EmbedContentBatch.java @@ -0,0 +1,140 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 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.errorprone.annotations.CanIgnoreReturnValue; +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. + */ + @CanIgnoreReturnValue + 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. + */ + @CanIgnoreReturnValue + public Builder contents(Content.Builder... contentsBuilders) { + return contents( + Arrays.asList(contentsBuilders).stream() + .map(Content.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder contents(Optional> contents); + + /** Clears the value of contents field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearContents() { + return contents(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder config(EmbedContentConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + 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..1f50e4729dc 100644 --- a/src/main/java/com/google/genai/types/EmbedContentConfig.java +++ b/src/main/java/com/google/genai/types/EmbedContentConfig.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; @@ -49,19 +50,34 @@ public abstract class EmbedContentConfig extends JsonSerializable { @JsonProperty("outputDimensionality") public abstract Optional outputDimensionality(); - /** Vertex API only. The MIME type of the input. */ + /** Gemini Enterprise Agent Platform only. The MIME type of the input. */ @JsonProperty("mimeType") public abstract Optional mimeType(); /** - * Vertex API only. Whether to silently truncate inputs longer than the max sequence length. If - * this option is set to false, oversized inputs will lead to an INVALID_ARGUMENT error, similar - * to other text APIs. + * Gemini Enterprise Agent Platform only. Whether to silently truncate inputs longer than the max + * sequence length. If this option is set to false, oversized inputs will lead to an + * INVALID_ARGUMENT error, similar to other text APIs. */ @JsonProperty("autoTruncate") public abstract Optional autoTruncate(); + /** + * Gemini Enterprise Agent Platform only. Whether to enable OCR for document content. Only + * applicable to Gemini Embedding 2 models. + */ + @JsonProperty("documentOcr") + public abstract Optional documentOcr(); + + /** + * Gemini Enterprise Agent Platform only. Whether to extract audio from video content. Only + * applicable to Gemini Embedding 2 models. + */ + @JsonProperty("audioTrackExtraction") + public abstract Optional audioTrackExtraction(); + /** Instantiates a builder for EmbedContentConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EmbedContentConfig.Builder(); } @@ -91,10 +107,21 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + /** * Setter for taskType. * @@ -103,6 +130,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("taskType") public abstract Builder taskType(String taskType); + @ExcludeFromGeneratedCoverageReport + abstract Builder taskType(Optional taskType); + + /** Clears the value of taskType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTaskType() { + return taskType(Optional.empty()); + } + /** * Setter for title. * @@ -111,6 +148,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("title") public abstract Builder title(String title); + @ExcludeFromGeneratedCoverageReport + abstract Builder title(Optional title); + + /** Clears the value of title field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTitle() { + return title(Optional.empty()); + } + /** * Setter for outputDimensionality. * @@ -121,28 +168,97 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("outputDimensionality") public abstract Builder outputDimensionality(Integer outputDimensionality); + @ExcludeFromGeneratedCoverageReport + abstract Builder outputDimensionality(Optional outputDimensionality); + + /** Clears the value of outputDimensionality field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputDimensionality() { + return outputDimensionality(Optional.empty()); + } + /** * Setter for mimeType. * - *

    mimeType: Vertex API only. The MIME type of the input. + *

    mimeType: Gemini Enterprise Agent Platform only. The MIME type of the input. */ @JsonProperty("mimeType") public abstract Builder mimeType(String mimeType); + @ExcludeFromGeneratedCoverageReport + abstract Builder mimeType(Optional mimeType); + + /** Clears the value of mimeType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMimeType() { + return mimeType(Optional.empty()); + } + /** * Setter for autoTruncate. * - *

    autoTruncate: Vertex API only. Whether to silently truncate inputs longer than the max - * sequence length. If this option is set to false, oversized inputs will lead to an - * INVALID_ARGUMENT error, similar to other text APIs. + *

    autoTruncate: Gemini Enterprise Agent Platform only. Whether to silently truncate inputs + * longer than the max sequence length. If this option is set to false, oversized inputs will + * lead to an INVALID_ARGUMENT error, similar to other text APIs. */ @JsonProperty("autoTruncate") public abstract Builder autoTruncate(boolean autoTruncate); + @ExcludeFromGeneratedCoverageReport + abstract Builder autoTruncate(Optional autoTruncate); + + /** Clears the value of autoTruncate field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAutoTruncate() { + return autoTruncate(Optional.empty()); + } + + /** + * Setter for documentOcr. + * + *

    documentOcr: Gemini Enterprise Agent Platform only. Whether to enable OCR for document + * content. Only applicable to Gemini Embedding 2 models. + */ + @JsonProperty("documentOcr") + public abstract Builder documentOcr(boolean documentOcr); + + @ExcludeFromGeneratedCoverageReport + abstract Builder documentOcr(Optional documentOcr); + + /** Clears the value of documentOcr field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDocumentOcr() { + return documentOcr(Optional.empty()); + } + + /** + * Setter for audioTrackExtraction. + * + *

    audioTrackExtraction: Gemini Enterprise Agent Platform only. Whether to extract audio from + * video content. Only applicable to Gemini Embedding 2 models. + */ + @JsonProperty("audioTrackExtraction") + public abstract Builder audioTrackExtraction(boolean audioTrackExtraction); + + @ExcludeFromGeneratedCoverageReport + abstract Builder audioTrackExtraction(Optional audioTrackExtraction); + + /** Clears the value of audioTrackExtraction field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAudioTrackExtraction() { + return audioTrackExtraction(Optional.empty()); + } + public abstract EmbedContentConfig build(); } /** 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..959308828df 100644 --- a/src/main/java/com/google/genai/types/EmbedContentMetadata.java +++ b/src/main/java/com/google/genai/types/EmbedContentMetadata.java @@ -22,18 +22,23 @@ 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; -/** Request-level metadata for the Vertex Embed Content API. */ +/** Request-level metadata for the Gemini Enterprise Agent Platform Embed Content API. */ @AutoValue @JsonDeserialize(builder = EmbedContentMetadata.Builder.class) public abstract class EmbedContentMetadata extends JsonSerializable { - /** Vertex API only. The total number of billable characters included in the request. */ + /** + * Gemini Enterprise Agent Platform only. The total number of billable characters included in the + * request. + */ @JsonProperty("billableCharacterCount") public abstract Optional billableCharacterCount(); /** Instantiates a builder for EmbedContentMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EmbedContentMetadata.Builder(); } @@ -53,16 +58,27 @@ private static Builder create() { /** * Setter for billableCharacterCount. * - *

    billableCharacterCount: Vertex API only. The total number of billable characters included - * in the request. + *

    billableCharacterCount: Gemini Enterprise Agent Platform only. The total number of + * billable characters included in the request. */ @JsonProperty("billableCharacterCount") public abstract Builder billableCharacterCount(Integer billableCharacterCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder billableCharacterCount(Optional billableCharacterCount); + + /** Clears the value of billableCharacterCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBillableCharacterCount() { + return billableCharacterCount(Optional.empty()); + } + public abstract EmbedContentMetadata build(); } /** 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..882b97dede7 100644 --- a/src/main/java/com/google/genai/types/EmbedContentParameters.java +++ b/src/main/java/com/google/genai/types/EmbedContentParameters.java @@ -25,6 +25,7 @@ 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.Arrays; import java.util.List; @@ -51,6 +52,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(); } @@ -76,6 +78,16 @@ private static Builder create() { @JsonProperty("model") public abstract Builder model(String model); + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + /** * Setter for contents. * @@ -89,6 +101,7 @@ private static Builder create() { * *

    contents: The content to embed. Only the `parts.text` fields will be counted. */ + @CanIgnoreReturnValue public Builder contents(Content... contents) { return contents(Arrays.asList(contents)); } @@ -98,6 +111,7 @@ public Builder contents(Content... contents) { * *

    contents: The content to embed. Only the `parts.text` fields will be counted. */ + @CanIgnoreReturnValue public Builder contents(Content.Builder... contentsBuilders) { return contents( Arrays.asList(contentsBuilders).stream() @@ -105,6 +119,16 @@ public Builder contents(Content.Builder... contentsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder contents(Optional> contents); + + /** Clears the value of contents field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearContents() { + return contents(Optional.empty()); + } + /** * Setter for config. * @@ -118,14 +142,26 @@ public Builder contents(Content.Builder... contentsBuilders) { * *

    config: Configuration that contains optional parameters. */ + @CanIgnoreReturnValue public Builder config(EmbedContentConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract EmbedContentParameters build(); } /** 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/EmbedContentParametersPrivate.java b/src/main/java/com/google/genai/types/EmbedContentParametersPrivate.java new file mode 100644 index 00000000000..756e4356c5c --- /dev/null +++ b/src/main/java/com/google/genai/types/EmbedContentParametersPrivate.java @@ -0,0 +1,244 @@ +/* + * 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.api.core.InternalApi; +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; + +/** Parameters for the _embed_content method. */ +@AutoValue +@InternalApi +@JsonDeserialize(builder = EmbedContentParametersPrivate.Builder.class) +public abstract class EmbedContentParametersPrivate extends JsonSerializable { + /** + * ID of the model to use. For a list of models, see `Google models + * `_. + */ + @JsonProperty("model") + public abstract Optional model(); + + /** The content to embed. Only the `parts.text` fields will be counted. */ + @JsonProperty("contents") + public abstract Optional> contents(); + + /** The single content to embed. Only the `parts.text` fields will be counted. */ + @JsonProperty("content") + public abstract Optional content(); + + /** The Gemini Enterprise Agent Platform embedding API to use. */ + @JsonProperty("embeddingApiType") + public abstract Optional embeddingApiType(); + + /** Configuration that contains optional parameters. */ + @JsonProperty("config") + public abstract Optional config(); + + /** Instantiates a builder for EmbedContentParametersPrivate. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_EmbedContentParametersPrivate.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for EmbedContentParametersPrivate. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `EmbedContentParametersPrivate.builder()` for instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_EmbedContentParametersPrivate.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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + 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. + */ + @CanIgnoreReturnValue + public Builder contents(Content.Builder... contentsBuilders) { + return contents( + Arrays.asList(contentsBuilders).stream() + .map(Content.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder contents(Optional> contents); + + /** Clears the value of contents field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearContents() { + return contents(Optional.empty()); + } + + /** + * Setter for content. + * + *

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

    content: The single content to embed. Only the `parts.text` fields will be counted. + */ + @CanIgnoreReturnValue + public Builder content(Content.Builder contentBuilder) { + return content(contentBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder content(Optional content); + + /** Clears the value of content field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearContent() { + return content(Optional.empty()); + } + + /** + * Setter for embeddingApiType. + * + *

    embeddingApiType: The Gemini Enterprise Agent Platform embedding API to use. + */ + @JsonProperty("embeddingApiType") + public abstract Builder embeddingApiType(EmbeddingApiType embeddingApiType); + + @ExcludeFromGeneratedCoverageReport + abstract Builder embeddingApiType(Optional embeddingApiType); + + /** Clears the value of embeddingApiType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEmbeddingApiType() { + return embeddingApiType(Optional.empty()); + } + + /** + * Setter for embeddingApiType given a known enum. + * + *

    embeddingApiType: The Gemini Enterprise Agent Platform embedding API to use. + */ + @CanIgnoreReturnValue + public Builder embeddingApiType(EmbeddingApiType.Known knownType) { + return embeddingApiType(new EmbeddingApiType(knownType)); + } + + /** + * Setter for embeddingApiType given a string. + * + *

    embeddingApiType: The Gemini Enterprise Agent Platform embedding API to use. + */ + @CanIgnoreReturnValue + public Builder embeddingApiType(String embeddingApiType) { + return embeddingApiType(new EmbeddingApiType(embeddingApiType)); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder config(EmbedContentConfig.Builder configBuilder) { + return config(configBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + + public abstract EmbedContentParametersPrivate build(); + } + + /** Deserializes a JSON string to a EmbedContentParametersPrivate object. */ + @ExcludeFromGeneratedCoverageReport + public static EmbedContentParametersPrivate fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, EmbedContentParametersPrivate.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..91fba94e507 100644 --- a/src/main/java/com/google/genai/types/EmbedContentResponse.java +++ b/src/main/java/com/google/genai/types/EmbedContentResponse.java @@ -24,6 +24,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.Arrays; import java.util.List; @@ -33,15 +34,20 @@ @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(); - /** Vertex API only. Metadata about the request. */ + /** Gemini Enterprise Agent Platform only. Metadata about the request. */ @JsonProperty("metadata") public abstract Optional metadata(); /** Instantiates a builder for EmbedContentResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_EmbedContentResponse.Builder(); } @@ -58,6 +64,34 @@ 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. + */ + @CanIgnoreReturnValue + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + /** * Setter for embeddings. * @@ -73,6 +107,7 @@ private static Builder create() { *

    embeddings: The embeddings for each request, in the same order as provided in the batch * request. */ + @CanIgnoreReturnValue public Builder embeddings(ContentEmbedding... embeddings) { return embeddings(Arrays.asList(embeddings)); } @@ -83,6 +118,7 @@ public Builder embeddings(ContentEmbedding... embeddings) { *

    embeddings: The embeddings for each request, in the same order as provided in the batch * request. */ + @CanIgnoreReturnValue public Builder embeddings(ContentEmbedding.Builder... embeddingsBuilders) { return embeddings( Arrays.asList(embeddingsBuilders).stream() @@ -90,10 +126,20 @@ public Builder embeddings(ContentEmbedding.Builder... embeddingsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder embeddings(Optional> embeddings); + + /** Clears the value of embeddings field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEmbeddings() { + return embeddings(Optional.empty()); + } + /** * Setter for metadata. * - *

    metadata: Vertex API only. Metadata about the request. + *

    metadata: Gemini Enterprise Agent Platform only. Metadata about the request. */ @JsonProperty("metadata") public abstract Builder metadata(EmbedContentMetadata metadata); @@ -101,16 +147,28 @@ public Builder embeddings(ContentEmbedding.Builder... embeddingsBuilders) { /** * Setter for metadata builder. * - *

    metadata: Vertex API only. Metadata about the request. + *

    metadata: Gemini Enterprise Agent Platform only. Metadata about the request. */ + @CanIgnoreReturnValue public Builder metadata(EmbedContentMetadata.Builder metadataBuilder) { return metadata(metadataBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder metadata(Optional metadata); + + /** Clears the value of metadata field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMetadata() { + return metadata(Optional.empty()); + } + public abstract EmbedContentResponse build(); } /** 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/EmbeddingApiType.java b/src/main/java/com/google/genai/types/EmbeddingApiType.java new file mode 100644 index 00000000000..d4b9eec037a --- /dev/null +++ b/src/main/java/com/google/genai/types/EmbeddingApiType.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 Gemini Enterprise Agent Platform embedding API to use. */ +public class EmbeddingApiType { + + /** Enum representing the known values for EmbeddingApiType. */ + public enum Known { + /** predict API endpoint (default) */ + PREDICT, + + /** embedContent API Endpoint */ + EMBED_CONTENT, + + EMBEDDING_API_TYPE_UNSPECIFIED + } + + private Known embeddingApiTypeEnum; + private final String value; + + @JsonCreator + public EmbeddingApiType(String value) { + this.value = value; + for (Known embeddingApiTypeEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(embeddingApiTypeEnum.toString(), value)) { + this.embeddingApiTypeEnum = embeddingApiTypeEnum; + break; + } + } + if (this.embeddingApiTypeEnum == null) { + this.embeddingApiTypeEnum = Known.EMBEDDING_API_TYPE_UNSPECIFIED; + } + } + + public EmbeddingApiType(Known knownValue) { + this.embeddingApiTypeEnum = 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 EmbeddingApiType)) { + return false; + } + + EmbeddingApiType other = (EmbeddingApiType) o; + + if (this.embeddingApiTypeEnum != Known.EMBEDDING_API_TYPE_UNSPECIFIED + && other.embeddingApiTypeEnum != Known.EMBEDDING_API_TYPE_UNSPECIFIED) { + return this.embeddingApiTypeEnum == other.embeddingApiTypeEnum; + } else if (this.embeddingApiTypeEnum == Known.EMBEDDING_API_TYPE_UNSPECIFIED + && other.embeddingApiTypeEnum == Known.EMBEDDING_API_TYPE_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.embeddingApiTypeEnum != Known.EMBEDDING_API_TYPE_UNSPECIFIED) { + return this.embeddingApiTypeEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.embeddingApiTypeEnum; + } +} 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..c7838f0a243 --- /dev/null +++ b/src/main/java/com/google/genai/types/EmbeddingsBatchJobSource.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.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; + +/** 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder fileName(Optional fileName); + + /** Clears the value of fileName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFileName() { + return fileName(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder inlinedRequests(EmbedContentBatch.Builder inlinedRequestsBuilder) { + return inlinedRequests(inlinedRequestsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder inlinedRequests(Optional inlinedRequests); + + /** Clears the value of inlinedRequests field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearInlinedRequests() { + return inlinedRequests(Optional.empty()); + } + + 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 new file mode 100644 index 00000000000..947f7b26303 --- /dev/null +++ b/src/main/java/com/google/genai/types/EncryptionSpec.java @@ -0,0 +1,90 @@ +/* + * 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; + +/** + * Represents a customer-managed encryption key specification that can be applied to a Vertex AI + * resource. This data type is not supported in Gemini API. + */ +@AutoValue +@JsonDeserialize(builder = EncryptionSpec.Builder.class) +public abstract class EncryptionSpec extends JsonSerializable { + /** + * Required. Resource name of the Cloud KMS key used to protect the resource. The Cloud KMS key + * must be in the same region as the resource. It must have the format + * `projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`. + */ + @JsonProperty("kmsKeyName") + public abstract Optional kmsKeyName(); + + /** Instantiates a builder for EncryptionSpec. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_EncryptionSpec.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for EncryptionSpec. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `EncryptionSpec.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_EncryptionSpec.Builder(); + } + + /** + * Setter for kmsKeyName. + * + *

    kmsKeyName: Required. Resource name of the Cloud KMS key used to protect the resource. The + * Cloud KMS key must be in the same region as the resource. It must have the format + * `projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`. + */ + @JsonProperty("kmsKeyName") + public abstract Builder kmsKeyName(String kmsKeyName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder kmsKeyName(Optional kmsKeyName); + + /** Clears the value of kmsKeyName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearKmsKeyName() { + return kmsKeyName(Optional.empty()); + } + + public abstract EncryptionSpec build(); + } + + /** 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..66ec39d54b6 100644 --- a/src/main/java/com/google/genai/types/Endpoint.java +++ b/src/main/java/com/google/genai/types/Endpoint.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; @@ -38,6 +39,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(); } @@ -62,6 +64,16 @@ private static Builder create() { @JsonProperty("name") public abstract Builder name(String name); + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + /** * Setter for deployedModelId. * @@ -70,10 +82,21 @@ private static Builder create() { @JsonProperty("deployedModelId") public abstract Builder deployedModelId(String deployedModelId); + @ExcludeFromGeneratedCoverageReport + abstract Builder deployedModelId(Optional deployedModelId); + + /** Clears the value of deployedModelId field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDeployedModelId() { + return deployedModelId(Optional.empty()); + } + public abstract Endpoint build(); } /** 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..d198d0703c7 100644 --- a/src/main/java/com/google/genai/types/EnterpriseWebSearch.java +++ b/src/main/java/com/google/genai/types/EnterpriseWebSearch.java @@ -19,15 +19,38 @@ 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 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. Sites with confidence level chosen & above this value will be blocked from the search + * results. + */ + @JsonProperty("blockingConfidence") + public abstract Optional blockingConfidence(); + + /** + * 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 +67,82 @@ private static Builder create() { return new AutoValue_EnterpriseWebSearch.Builder(); } + /** + * Setter for blockingConfidence. + * + *

    blockingConfidence: Optional. Sites with confidence level chosen & above this value will + * be blocked from the search results. + */ + @JsonProperty("blockingConfidence") + public abstract Builder blockingConfidence(PhishBlockThreshold blockingConfidence); + + @ExcludeFromGeneratedCoverageReport + abstract Builder blockingConfidence(Optional blockingConfidence); + + /** Clears the value of blockingConfidence field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBlockingConfidence() { + return blockingConfidence(Optional.empty()); + } + + /** + * Setter for blockingConfidence given a known enum. + * + *

    blockingConfidence: Optional. Sites with confidence level chosen & above this value will + * be blocked from the search results. + */ + @CanIgnoreReturnValue + public Builder blockingConfidence(PhishBlockThreshold.Known knownType) { + return blockingConfidence(new PhishBlockThreshold(knownType)); + } + + /** + * Setter for blockingConfidence given a string. + * + *

    blockingConfidence: Optional. Sites with confidence level chosen & above this value will + * be blocked from the search results. + */ + @CanIgnoreReturnValue + public Builder blockingConfidence(String blockingConfidence) { + return blockingConfidence(new PhishBlockThreshold(blockingConfidence)); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder excludeDomains(String... excludeDomains) { + return excludeDomains(Arrays.asList(excludeDomains)); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder excludeDomains(Optional> excludeDomains); + + /** Clears the value of excludeDomains field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearExcludeDomains() { + return excludeDomains(Optional.empty()); + } + 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..533708a1f80 --- /dev/null +++ b/src/main/java/com/google/genai/types/EntityLabel.java @@ -0,0 +1,103 @@ +/* + * 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; + +/** 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder label(Optional label); + + /** Clears the value of label field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLabel() { + return label(Optional.empty()); + } + + /** + * Setter for score. + * + *

    score: The confidence score of the detected label. + */ + @JsonProperty("score") + public abstract Builder score(Float score); + + @ExcludeFromGeneratedCoverageReport + abstract Builder score(Optional score); + + /** Clears the value of score field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearScore() { + return score(Optional.empty()); + } + + 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 new file mode 100644 index 00000000000..4fefd958a0a --- /dev/null +++ b/src/main/java/com/google/genai/types/Environment.java @@ -0,0 +1,108 @@ +/* + * 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 environment being operated. */ +public class Environment { + + /** Enum representing the known values for Environment. */ + public enum Known { + /** Defaults to browser. */ + ENVIRONMENT_UNSPECIFIED, + + /** Operates in a web browser. */ + ENVIRONMENT_BROWSER + } + + private Known environmentEnum; + private final String value; + + @JsonCreator + public Environment(String value) { + this.value = value; + for (Known environmentEnum : Known.values()) { + if (Ascii.equalsIgnoreCase(environmentEnum.toString(), value)) { + this.environmentEnum = environmentEnum; + break; + } + } + if (this.environmentEnum == null) { + this.environmentEnum = Known.ENVIRONMENT_UNSPECIFIED; + } + } + + public Environment(Known knownValue) { + this.environmentEnum = 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 Environment)) { + return false; + } + + Environment other = (Environment) o; + + if (this.environmentEnum != Known.ENVIRONMENT_UNSPECIFIED + && other.environmentEnum != Known.ENVIRONMENT_UNSPECIFIED) { + return this.environmentEnum == other.environmentEnum; + } else if (this.environmentEnum == Known.ENVIRONMENT_UNSPECIFIED + && other.environmentEnum == Known.ENVIRONMENT_UNSPECIFIED) { + return this.value.equals(other.value); + } + return false; + } + + @ExcludeFromGeneratedCoverageReport + @Override + public int hashCode() { + if (this.environmentEnum != Known.ENVIRONMENT_UNSPECIFIED) { + return this.environmentEnum.hashCode(); + } else { + return Objects.hashCode(this.value); + } + } + + @ExcludeFromGeneratedCoverageReport + public Known knownEnum() { + return this.environmentEnum; + } +} diff --git a/src/main/java/com/google/genai/types/EvaluateDatasetResponse.java b/src/main/java/com/google/genai/types/EvaluateDatasetResponse.java new file mode 100644 index 00000000000..75fa4c58ec8 --- /dev/null +++ b/src/main/java/com/google/genai/types/EvaluateDatasetResponse.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 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; + +/** + * The results from an evaluation run performed by the EvaluationService. This data type is not + * supported in Gemini API. + */ +@AutoValue +@JsonDeserialize(builder = EvaluateDatasetResponse.Builder.class) +public abstract class EvaluateDatasetResponse extends JsonSerializable { + /** Output only. Aggregation statistics derived from results of EvaluationService. */ + @JsonProperty("aggregationOutput") + public abstract Optional aggregationOutput(); + + /** Output only. Output info for EvaluationService. */ + @JsonProperty("outputInfo") + public abstract Optional outputInfo(); + + /** Instantiates a builder for EvaluateDatasetResponse. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_EvaluateDatasetResponse.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for EvaluateDatasetResponse. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `EvaluateDatasetResponse.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_EvaluateDatasetResponse.Builder(); + } + + /** + * Setter for aggregationOutput. + * + *

    aggregationOutput: Output only. Aggregation statistics derived from results of + * EvaluationService. + */ + @JsonProperty("aggregationOutput") + public abstract Builder aggregationOutput(AggregationOutput aggregationOutput); + + /** + * Setter for aggregationOutput builder. + * + *

    aggregationOutput: Output only. Aggregation statistics derived from results of + * EvaluationService. + */ + @CanIgnoreReturnValue + public Builder aggregationOutput(AggregationOutput.Builder aggregationOutputBuilder) { + return aggregationOutput(aggregationOutputBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder aggregationOutput(Optional aggregationOutput); + + /** Clears the value of aggregationOutput field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAggregationOutput() { + return aggregationOutput(Optional.empty()); + } + + /** + * Setter for outputInfo. + * + *

    outputInfo: Output only. Output info for EvaluationService. + */ + @JsonProperty("outputInfo") + public abstract Builder outputInfo(OutputInfo outputInfo); + + /** + * Setter for outputInfo builder. + * + *

    outputInfo: Output only. Output info for EvaluationService. + */ + @CanIgnoreReturnValue + public Builder outputInfo(OutputInfo.Builder outputInfoBuilder) { + return outputInfo(outputInfoBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder outputInfo(Optional outputInfo); + + /** Clears the value of outputInfo field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputInfo() { + return outputInfo(Optional.empty()); + } + + public abstract EvaluateDatasetResponse build(); + } + + /** Deserializes a JSON string to a EvaluateDatasetResponse object. */ + @ExcludeFromGeneratedCoverageReport + public static EvaluateDatasetResponse fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, EvaluateDatasetResponse.class); + } +} diff --git a/src/main/java/com/google/genai/types/EvaluateDatasetRun.java b/src/main/java/com/google/genai/types/EvaluateDatasetRun.java new file mode 100644 index 00000000000..a0fadae278e --- /dev/null +++ b/src/main/java/com/google/genai/types/EvaluateDatasetRun.java @@ -0,0 +1,201 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 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; + +/** Evaluate Dataset Run Result for Tuning Job. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = EvaluateDatasetRun.Builder.class) +public abstract class EvaluateDatasetRun extends JsonSerializable { + /** + * Output only. The checkpoint id used in the evaluation run. Only populated when evaluating + * checkpoints. + */ + @JsonProperty("checkpointId") + public abstract Optional checkpointId(); + + /** Output only. The error of the evaluation run if any. */ + @JsonProperty("error") + public abstract Optional error(); + + /** Output only. Results for EvaluationService. */ + @JsonProperty("evaluateDatasetResponse") + public abstract Optional evaluateDatasetResponse(); + + /** + * Output only. The resource name of the evaluation run. Format: + * `projects/{project}/locations/{location}/evaluationRuns/{evaluation_run_id}`. + */ + @JsonProperty("evaluationRun") + public abstract Optional evaluationRun(); + + /** Output only. Deprecated: The updated architecture uses evaluation_run instead. */ + @JsonProperty("operationName") + public abstract Optional operationName(); + + /** Instantiates a builder for EvaluateDatasetRun. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_EvaluateDatasetRun.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for EvaluateDatasetRun. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `EvaluateDatasetRun.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_EvaluateDatasetRun.Builder(); + } + + /** + * Setter for checkpointId. + * + *

    checkpointId: Output only. The checkpoint id used in the evaluation run. Only populated + * when evaluating checkpoints. + */ + @JsonProperty("checkpointId") + public abstract Builder checkpointId(String checkpointId); + + @ExcludeFromGeneratedCoverageReport + abstract Builder checkpointId(Optional checkpointId); + + /** Clears the value of checkpointId field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCheckpointId() { + return checkpointId(Optional.empty()); + } + + /** + * Setter for error. + * + *

    error: Output only. The error of the evaluation run if any. + */ + @JsonProperty("error") + public abstract Builder error(GoogleRpcStatus error); + + /** + * Setter for error builder. + * + *

    error: Output only. The error of the evaluation run if any. + */ + @CanIgnoreReturnValue + public Builder error(GoogleRpcStatus.Builder errorBuilder) { + return error(errorBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder error(Optional error); + + /** Clears the value of error field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearError() { + return error(Optional.empty()); + } + + /** + * Setter for evaluateDatasetResponse. + * + *

    evaluateDatasetResponse: Output only. Results for EvaluationService. + */ + @JsonProperty("evaluateDatasetResponse") + public abstract Builder evaluateDatasetResponse( + EvaluateDatasetResponse evaluateDatasetResponse); + + /** + * Setter for evaluateDatasetResponse builder. + * + *

    evaluateDatasetResponse: Output only. Results for EvaluationService. + */ + @CanIgnoreReturnValue + public Builder evaluateDatasetResponse( + EvaluateDatasetResponse.Builder evaluateDatasetResponseBuilder) { + return evaluateDatasetResponse(evaluateDatasetResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder evaluateDatasetResponse( + Optional evaluateDatasetResponse); + + /** Clears the value of evaluateDatasetResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEvaluateDatasetResponse() { + return evaluateDatasetResponse(Optional.empty()); + } + + /** + * Setter for evaluationRun. + * + *

    evaluationRun: Output only. The resource name of the evaluation run. Format: + * `projects/{project}/locations/{location}/evaluationRuns/{evaluation_run_id}`. + */ + @JsonProperty("evaluationRun") + public abstract Builder evaluationRun(String evaluationRun); + + @ExcludeFromGeneratedCoverageReport + abstract Builder evaluationRun(Optional evaluationRun); + + /** Clears the value of evaluationRun field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEvaluationRun() { + return evaluationRun(Optional.empty()); + } + + /** + * Setter for operationName. + * + *

    operationName: Output only. Deprecated: The updated architecture uses evaluation_run + * instead. + */ + @JsonProperty("operationName") + public abstract Builder operationName(String operationName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder operationName(Optional operationName); + + /** Clears the value of operationName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOperationName() { + return operationName(Optional.empty()); + } + + public abstract EvaluateDatasetRun build(); + } + + /** Deserializes a JSON string to a EvaluateDatasetRun object. */ + @ExcludeFromGeneratedCoverageReport + public static EvaluateDatasetRun fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, EvaluateDatasetRun.class); + } +} diff --git a/src/main/java/com/google/genai/types/EvaluationConfig.java b/src/main/java/com/google/genai/types/EvaluationConfig.java new file mode 100644 index 00000000000..3e452209de8 --- /dev/null +++ b/src/main/java/com/google/genai/types/EvaluationConfig.java @@ -0,0 +1,206 @@ +/* + * 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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** Evaluation config for tuning. */ +@AutoValue +@JsonDeserialize(builder = EvaluationConfig.Builder.class) +public abstract class EvaluationConfig extends JsonSerializable { + /** The metrics used for evaluation. */ + @JsonProperty("metrics") + public abstract Optional> metrics(); + + /** Config for evaluation output. */ + @JsonProperty("outputConfig") + public abstract Optional outputConfig(); + + /** Autorater config for evaluation. */ + @JsonProperty("autoraterConfig") + public abstract Optional autoraterConfig(); + + /** Generation config for inference. */ + @JsonProperty("inferenceGenerationConfig") + public abstract Optional inferenceGenerationConfig(); + + /** Instantiates a builder for EvaluationConfig. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_EvaluationConfig.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for EvaluationConfig. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `EvaluationConfig.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_EvaluationConfig.Builder(); + } + + /** + * Setter for metrics. + * + *

    metrics: The metrics used for evaluation. + */ + @JsonProperty("metrics") + public abstract Builder metrics(List metrics); + + /** + * Setter for metrics. + * + *

    metrics: The metrics used for evaluation. + */ + @CanIgnoreReturnValue + public Builder metrics(UnifiedMetric... metrics) { + return metrics(Arrays.asList(metrics)); + } + + /** + * Setter for metrics builder. + * + *

    metrics: The metrics used for evaluation. + */ + @CanIgnoreReturnValue + public Builder metrics(UnifiedMetric.Builder... metricsBuilders) { + return metrics( + Arrays.asList(metricsBuilders).stream() + .map(UnifiedMetric.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder metrics(Optional> metrics); + + /** Clears the value of metrics field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMetrics() { + return metrics(Optional.empty()); + } + + /** + * Setter for outputConfig. + * + *

    outputConfig: Config for evaluation output. + */ + @JsonProperty("outputConfig") + public abstract Builder outputConfig(OutputConfig outputConfig); + + /** + * Setter for outputConfig builder. + * + *

    outputConfig: Config for evaluation output. + */ + @CanIgnoreReturnValue + public Builder outputConfig(OutputConfig.Builder outputConfigBuilder) { + return outputConfig(outputConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder outputConfig(Optional outputConfig); + + /** Clears the value of outputConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputConfig() { + return outputConfig(Optional.empty()); + } + + /** + * Setter for autoraterConfig. + * + *

    autoraterConfig: Autorater config for evaluation. + */ + @JsonProperty("autoraterConfig") + public abstract Builder autoraterConfig(AutoraterConfig autoraterConfig); + + /** + * Setter for autoraterConfig builder. + * + *

    autoraterConfig: Autorater config for evaluation. + */ + @CanIgnoreReturnValue + public Builder autoraterConfig(AutoraterConfig.Builder autoraterConfigBuilder) { + return autoraterConfig(autoraterConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder autoraterConfig(Optional autoraterConfig); + + /** Clears the value of autoraterConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAutoraterConfig() { + return autoraterConfig(Optional.empty()); + } + + /** + * Setter for inferenceGenerationConfig. + * + *

    inferenceGenerationConfig: Generation config for inference. + */ + @JsonProperty("inferenceGenerationConfig") + public abstract Builder inferenceGenerationConfig(GenerationConfig inferenceGenerationConfig); + + /** + * Setter for inferenceGenerationConfig builder. + * + *

    inferenceGenerationConfig: Generation config for inference. + */ + @CanIgnoreReturnValue + public Builder inferenceGenerationConfig( + GenerationConfig.Builder inferenceGenerationConfigBuilder) { + return inferenceGenerationConfig(inferenceGenerationConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder inferenceGenerationConfig( + Optional inferenceGenerationConfig); + + /** Clears the value of inferenceGenerationConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearInferenceGenerationConfig() { + return inferenceGenerationConfig(Optional.empty()); + } + + public abstract EvaluationConfig build(); + } + + /** Deserializes a JSON string to a EvaluationConfig object. */ + @ExcludeFromGeneratedCoverageReport + public static EvaluationConfig fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, EvaluationConfig.class); + } +} diff --git a/src/main/java/com/google/genai/types/EvaluationDataset.java b/src/main/java/com/google/genai/types/EvaluationDataset.java new file mode 100644 index 00000000000..4d9cf7d35a6 --- /dev/null +++ b/src/main/java/com/google/genai/types/EvaluationDataset.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 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; + +/** The dataset used for evaluation. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = EvaluationDataset.Builder.class) +public abstract class EvaluationDataset extends JsonSerializable { + /** BigQuery source holds the dataset. */ + @JsonProperty("bigquerySource") + public abstract Optional bigquerySource(); + + /** + * Cloud storage source holds the dataset. Currently only one Cloud Storage file path is + * supported. + */ + @JsonProperty("gcsSource") + public abstract Optional gcsSource(); + + /** Instantiates a builder for EvaluationDataset. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_EvaluationDataset.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for EvaluationDataset. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `EvaluationDataset.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_EvaluationDataset.Builder(); + } + + /** + * Setter for bigquerySource. + * + *

    bigquerySource: BigQuery source holds the dataset. + */ + @JsonProperty("bigquerySource") + public abstract Builder bigquerySource(BigQuerySource bigquerySource); + + /** + * Setter for bigquerySource builder. + * + *

    bigquerySource: BigQuery source holds the dataset. + */ + @CanIgnoreReturnValue + public Builder bigquerySource(BigQuerySource.Builder bigquerySourceBuilder) { + return bigquerySource(bigquerySourceBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder bigquerySource(Optional bigquerySource); + + /** Clears the value of bigquerySource field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBigquerySource() { + return bigquerySource(Optional.empty()); + } + + /** + * Setter for gcsSource. + * + *

    gcsSource: Cloud storage source holds the dataset. Currently only one Cloud Storage file + * path is supported. + */ + @JsonProperty("gcsSource") + public abstract Builder gcsSource(GcsSource gcsSource); + + /** + * Setter for gcsSource builder. + * + *

    gcsSource: Cloud storage source holds the dataset. Currently only one Cloud Storage file + * path is supported. + */ + @CanIgnoreReturnValue + public Builder gcsSource(GcsSource.Builder gcsSourceBuilder) { + return gcsSource(gcsSourceBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder gcsSource(Optional gcsSource); + + /** Clears the value of gcsSource field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGcsSource() { + return gcsSource(Optional.empty()); + } + + public abstract EvaluationDataset build(); + } + + /** Deserializes a JSON string to a EvaluationDataset object. */ + @ExcludeFromGeneratedCoverageReport + public static EvaluationDataset fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, EvaluationDataset.class); + } +} diff --git a/src/main/java/com/google/genai/types/ExactMatchMetricValue.java b/src/main/java/com/google/genai/types/ExactMatchMetricValue.java new file mode 100644 index 00000000000..7a241f2ba46 --- /dev/null +++ b/src/main/java/com/google/genai/types/ExactMatchMetricValue.java @@ -0,0 +1,81 @@ +/* + * 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; + +/** Exact match metric value for an instance. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = ExactMatchMetricValue.Builder.class) +public abstract class ExactMatchMetricValue extends JsonSerializable { + /** Output only. Exact match score. */ + @JsonProperty("score") + public abstract Optional score(); + + /** Instantiates a builder for ExactMatchMetricValue. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ExactMatchMetricValue.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ExactMatchMetricValue. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ExactMatchMetricValue.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ExactMatchMetricValue.Builder(); + } + + /** + * Setter for score. + * + *

    score: Output only. Exact match score. + */ + @JsonProperty("score") + public abstract Builder score(Float score); + + @ExcludeFromGeneratedCoverageReport + abstract Builder score(Optional score); + + /** Clears the value of score field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearScore() { + return score(Optional.empty()); + } + + public abstract ExactMatchMetricValue build(); + } + + /** Deserializes a JSON string to a ExactMatchMetricValue object. */ + @ExcludeFromGeneratedCoverageReport + public static ExactMatchMetricValue fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, ExactMatchMetricValue.class); + } +} 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 f3a8181d0e6..0f2dcd27868 100644 --- a/src/main/java/com/google/genai/types/ExecutableCode.java +++ b/src/main/java/com/google/genai/types/ExecutableCode.java @@ -27,9 +27,10 @@ import java.util.Optional; /** - * Code generated by the model that is meant to be executed, and the result returned to the model. - * Generated when using the [FunctionDeclaration] tool and [FunctionCallingConfig] mode is set to - * [Mode.CODE]. + * Model-generated code executed server-side, results returned to the model. + * + *

    Only generated when using the `CodeExecution` tool, in which the code will be automatically + * executed, and a corresponding `CodeExecutionResult` will also be generated. */ @AutoValue @JsonDeserialize(builder = ExecutableCode.Builder.class) @@ -42,7 +43,15 @@ public abstract class ExecutableCode extends JsonSerializable { @JsonProperty("language") public abstract Optional language(); + /** + * Unique identifier of the `ExecutableCode` part. The server returns the `CodeExecutionResult` + * with the matching `id`. + */ + @JsonProperty("id") + public abstract Optional id(); + /** Instantiates a builder for ExecutableCode. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_ExecutableCode.Builder(); } @@ -67,6 +76,16 @@ private static Builder create() { @JsonProperty("code") public abstract Builder code(String code); + @ExcludeFromGeneratedCoverageReport + abstract Builder code(Optional code); + + /** Clears the value of code field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCode() { + return code(Optional.empty()); + } + /** * Setter for language. * @@ -75,20 +94,60 @@ private static Builder create() { @JsonProperty("language") public abstract Builder language(Language language); + @ExcludeFromGeneratedCoverageReport + abstract Builder language(Optional language); + + /** Clears the value of language field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLanguage() { + return language(Optional.empty()); + } + + /** + * Setter for language given a known enum. + * + *

    language: Required. Programming language of the `code`. + */ @CanIgnoreReturnValue public Builder language(Language.Known knownType) { return language(new Language(knownType)); } + /** + * Setter for language given a string. + * + *

    language: Required. Programming language of the `code`. + */ @CanIgnoreReturnValue public Builder language(String language) { return language(new Language(language)); } + /** + * Setter for id. + * + *

    id: Unique identifier of the `ExecutableCode` part. The server returns the + * `CodeExecutionResult` with the matching `id`. + */ + @JsonProperty("id") + public abstract Builder id(String id); + + @ExcludeFromGeneratedCoverageReport + abstract Builder id(Optional id); + + /** Clears the value of id field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearId() { + return id(Optional.empty()); + } + public abstract ExecutableCode build(); } /** 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 new file mode 100644 index 00000000000..d06f51707e0 --- /dev/null +++ b/src/main/java/com/google/genai/types/ExternalApi.java @@ -0,0 +1,264 @@ +/* + * 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; + +/** + * 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. This data type is not supported in Gemini + * API. + */ +@AutoValue +@JsonDeserialize(builder = ExternalApi.Builder.class) +public abstract class ExternalApi extends JsonSerializable { + /** The authentication config to access the API. Deprecated. Please use auth_config instead. */ + @JsonProperty("apiAuth") + public abstract Optional apiAuth(); + + /** The API spec that the external API implements. */ + @JsonProperty("apiSpec") + public abstract Optional apiSpec(); + + /** The authentication config to access the API. */ + @JsonProperty("authConfig") + public abstract Optional authConfig(); + + /** Parameters for the elastic search API. */ + @JsonProperty("elasticSearchParams") + public abstract Optional elasticSearchParams(); + + /** + * The endpoint of the external API. The system will call the API at this endpoint to retrieve the + * data for grounding. Example: https://acme.com:443/search + */ + @JsonProperty("endpoint") + public abstract Optional endpoint(); + + /** Parameters for the simple search API. */ + @JsonProperty("simpleSearchParams") + public abstract Optional simpleSearchParams(); + + /** Instantiates a builder for ExternalApi. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ExternalApi.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ExternalApi. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `ExternalApi.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_ExternalApi.Builder(); + } + + /** + * Setter for apiAuth. + * + *

    apiAuth: The authentication config to access the API. Deprecated. Please use auth_config + * instead. + */ + @JsonProperty("apiAuth") + public abstract Builder apiAuth(ApiAuth apiAuth); + + /** + * Setter for apiAuth builder. + * + *

    apiAuth: The authentication config to access the API. Deprecated. Please use auth_config + * instead. + */ + @CanIgnoreReturnValue + public Builder apiAuth(ApiAuth.Builder apiAuthBuilder) { + return apiAuth(apiAuthBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder apiAuth(Optional apiAuth); + + /** Clears the value of apiAuth field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearApiAuth() { + return apiAuth(Optional.empty()); + } + + /** + * Setter for apiSpec. + * + *

    apiSpec: The API spec that the external API implements. + */ + @JsonProperty("apiSpec") + public abstract Builder apiSpec(ApiSpec apiSpec); + + @ExcludeFromGeneratedCoverageReport + abstract Builder apiSpec(Optional apiSpec); + + /** Clears the value of apiSpec field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearApiSpec() { + return apiSpec(Optional.empty()); + } + + /** + * Setter for apiSpec given a known enum. + * + *

    apiSpec: The API spec that the external API implements. + */ + @CanIgnoreReturnValue + public Builder apiSpec(ApiSpec.Known knownType) { + return apiSpec(new ApiSpec(knownType)); + } + + /** + * Setter for apiSpec given a string. + * + *

    apiSpec: The API spec that the external API implements. + */ + @CanIgnoreReturnValue + public Builder apiSpec(String apiSpec) { + return apiSpec(new ApiSpec(apiSpec)); + } + + /** + * Setter for authConfig. + * + *

    authConfig: The authentication config to access the API. + */ + @JsonProperty("authConfig") + public abstract Builder authConfig(AuthConfig authConfig); + + /** + * Setter for authConfig builder. + * + *

    authConfig: The authentication config to access the API. + */ + @CanIgnoreReturnValue + public Builder authConfig(AuthConfig.Builder authConfigBuilder) { + return authConfig(authConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder authConfig(Optional authConfig); + + /** Clears the value of authConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAuthConfig() { + return authConfig(Optional.empty()); + } + + /** + * Setter for elasticSearchParams. + * + *

    elasticSearchParams: Parameters for the elastic search API. + */ + @JsonProperty("elasticSearchParams") + public abstract Builder elasticSearchParams(ExternalApiElasticSearchParams elasticSearchParams); + + /** + * Setter for elasticSearchParams builder. + * + *

    elasticSearchParams: Parameters for the elastic search API. + */ + @CanIgnoreReturnValue + public Builder elasticSearchParams( + ExternalApiElasticSearchParams.Builder elasticSearchParamsBuilder) { + return elasticSearchParams(elasticSearchParamsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder elasticSearchParams( + Optional elasticSearchParams); + + /** Clears the value of elasticSearchParams field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearElasticSearchParams() { + return elasticSearchParams(Optional.empty()); + } + + /** + * Setter for endpoint. + * + *

    endpoint: The endpoint of the external API. The system will call the API at this endpoint + * to retrieve the data for grounding. Example: https://acme.com:443/search + */ + @JsonProperty("endpoint") + public abstract Builder endpoint(String endpoint); + + @ExcludeFromGeneratedCoverageReport + abstract Builder endpoint(Optional endpoint); + + /** Clears the value of endpoint field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEndpoint() { + return endpoint(Optional.empty()); + } + + /** + * Setter for simpleSearchParams. + * + *

    simpleSearchParams: Parameters for the simple search API. + */ + @JsonProperty("simpleSearchParams") + public abstract Builder simpleSearchParams(ExternalApiSimpleSearchParams simpleSearchParams); + + /** + * Setter for simpleSearchParams builder. + * + *

    simpleSearchParams: Parameters for the simple search API. + */ + @CanIgnoreReturnValue + public Builder simpleSearchParams( + ExternalApiSimpleSearchParams.Builder simpleSearchParamsBuilder) { + return simpleSearchParams(simpleSearchParamsBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder simpleSearchParams(Optional simpleSearchParams); + + /** Clears the value of simpleSearchParams field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSimpleSearchParams() { + return simpleSearchParams(Optional.empty()); + } + + public abstract ExternalApi build(); + } + + /** 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 new file mode 100644 index 00000000000..52641a46d99 --- /dev/null +++ b/src/main/java/com/google/genai/types/ExternalApiElasticSearchParams.java @@ -0,0 +1,134 @@ +/* + * 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; + +/** + * 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 { + /** The ElasticSearch index to use. */ + @JsonProperty("index") + public abstract Optional index(); + + /** + * Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as + * the `num_hits` param. + */ + @JsonProperty("numHits") + public abstract Optional numHits(); + + /** The ElasticSearch search template to use. */ + @JsonProperty("searchTemplate") + public abstract Optional searchTemplate(); + + /** Instantiates a builder for ExternalApiElasticSearchParams. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_ExternalApiElasticSearchParams.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ExternalApiElasticSearchParams. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `ExternalApiElasticSearchParams.builder()` for instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_ExternalApiElasticSearchParams.Builder(); + } + + /** + * Setter for index. + * + *

    index: The ElasticSearch index to use. + */ + @JsonProperty("index") + public abstract Builder index(String index); + + @ExcludeFromGeneratedCoverageReport + abstract Builder index(Optional index); + + /** Clears the value of index field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearIndex() { + return index(Optional.empty()); + } + + /** + * Setter for numHits. + * + *

    numHits: Optional. Number of hits (chunks) to request. When specified, it is passed to + * Elasticsearch as the `num_hits` param. + */ + @JsonProperty("numHits") + public abstract Builder numHits(Integer numHits); + + @ExcludeFromGeneratedCoverageReport + abstract Builder numHits(Optional numHits); + + /** Clears the value of numHits field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearNumHits() { + return numHits(Optional.empty()); + } + + /** + * Setter for searchTemplate. + * + *

    searchTemplate: The ElasticSearch search template to use. + */ + @JsonProperty("searchTemplate") + public abstract Builder searchTemplate(String searchTemplate); + + @ExcludeFromGeneratedCoverageReport + abstract Builder searchTemplate(Optional searchTemplate); + + /** Clears the value of searchTemplate field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSearchTemplate() { + return searchTemplate(Optional.empty()); + } + + public abstract ExternalApiElasticSearchParams build(); + } + + /** 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 new file mode 100644 index 00000000000..b82a413cd90 --- /dev/null +++ b/src/main/java/com/google/genai/types/ExternalApiSimpleSearchParams.java @@ -0,0 +1,61 @@ +/* + * 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.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import com.google.genai.JsonSerializable; + +/** + * 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(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for ExternalApiSimpleSearchParams. */ + @AutoValue.Builder + public abstract static class Builder { + /** + * For internal usage. Please use `ExternalApiSimpleSearchParams.builder()` for instantiation. + */ + @JsonCreator + private static Builder create() { + return new AutoValue_ExternalApiSimpleSearchParams.Builder(); + } + + public abstract ExternalApiSimpleSearchParams build(); + } + + /** 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..d9720d77c2c 100644 --- a/src/main/java/com/google/genai/types/FetchPredictOperationConfig.java +++ b/src/main/java/com/google/genai/types/FetchPredictOperationConfig.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; @@ -34,6 +35,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(); } @@ -63,14 +65,26 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + public abstract FetchPredictOperationConfig build(); } /** 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..6f35fd8b759 100644 --- a/src/main/java/com/google/genai/types/FetchPredictOperationParameters.java +++ b/src/main/java/com/google/genai/types/FetchPredictOperationParameters.java @@ -23,6 +23,7 @@ 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; @@ -44,6 +45,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(); } @@ -70,6 +72,16 @@ private static Builder create() { @JsonProperty("operationName") public abstract Builder operationName(String operationName); + @ExcludeFromGeneratedCoverageReport + abstract Builder operationName(Optional operationName); + + /** Clears the value of operationName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOperationName() { + return operationName(Optional.empty()); + } + /** * Setter for resourceName. * @@ -78,6 +90,16 @@ private static Builder create() { @JsonProperty("resourceName") public abstract Builder resourceName(String resourceName); + @ExcludeFromGeneratedCoverageReport + abstract Builder resourceName(Optional resourceName); + + /** Clears the value of resourceName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResourceName() { + return resourceName(Optional.empty()); + } + /** * Setter for config. * @@ -91,14 +113,26 @@ private static Builder create() { * *

    config: Used to override the default configuration. */ + @CanIgnoreReturnValue public Builder config(FetchPredictOperationConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract FetchPredictOperationParameters build(); } /** 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 5216b6fb2d6..ac201db03c1 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(); } @@ -128,6 +129,16 @@ private static Builder create() { @JsonProperty("name") public abstract Builder name(String name); + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + /** * Setter for displayName. * @@ -137,6 +148,16 @@ private static Builder create() { @JsonProperty("displayName") public abstract Builder displayName(String displayName); + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + /** * Setter for mimeType. * @@ -145,6 +166,16 @@ private static Builder create() { @JsonProperty("mimeType") public abstract Builder mimeType(String mimeType); + @ExcludeFromGeneratedCoverageReport + abstract Builder mimeType(Optional mimeType); + + /** Clears the value of mimeType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMimeType() { + return mimeType(Optional.empty()); + } + /** * Setter for sizeBytes. * @@ -153,6 +184,16 @@ private static Builder create() { @JsonProperty("sizeBytes") public abstract Builder sizeBytes(Long sizeBytes); + @ExcludeFromGeneratedCoverageReport + abstract Builder sizeBytes(Optional sizeBytes); + + /** Clears the value of sizeBytes field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSizeBytes() { + return sizeBytes(Optional.empty()); + } + /** * Setter for createTime. * @@ -161,6 +202,16 @@ private static Builder create() { @JsonProperty("createTime") public abstract Builder createTime(Instant createTime); + @ExcludeFromGeneratedCoverageReport + abstract Builder createTime(Optional createTime); + + /** Clears the value of createTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCreateTime() { + return createTime(Optional.empty()); + } + /** * Setter for expirationTime. * @@ -170,6 +221,16 @@ private static Builder create() { @JsonProperty("expirationTime") public abstract Builder expirationTime(Instant expirationTime); + @ExcludeFromGeneratedCoverageReport + abstract Builder expirationTime(Optional expirationTime); + + /** Clears the value of expirationTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearExpirationTime() { + return expirationTime(Optional.empty()); + } + /** * Setter for updateTime. * @@ -178,6 +239,16 @@ private static Builder create() { @JsonProperty("updateTime") public abstract Builder updateTime(Instant updateTime); + @ExcludeFromGeneratedCoverageReport + abstract Builder updateTime(Optional updateTime); + + /** Clears the value of updateTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUpdateTime() { + return updateTime(Optional.empty()); + } + /** * Setter for sha256Hash. * @@ -187,6 +258,16 @@ private static Builder create() { @JsonProperty("sha256Hash") public abstract Builder sha256Hash(String sha256Hash); + @ExcludeFromGeneratedCoverageReport + abstract Builder sha256Hash(Optional sha256Hash); + + /** Clears the value of sha256Hash field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSha256Hash() { + return sha256Hash(Optional.empty()); + } + /** * Setter for uri. * @@ -195,6 +276,16 @@ private static Builder create() { @JsonProperty("uri") public abstract Builder uri(String uri); + @ExcludeFromGeneratedCoverageReport + abstract Builder uri(Optional uri); + + /** Clears the value of uri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUri() { + return uri(Optional.empty()); + } + /** * Setter for downloadUri. * @@ -204,6 +295,16 @@ private static Builder create() { @JsonProperty("downloadUri") public abstract Builder downloadUri(String downloadUri); + @ExcludeFromGeneratedCoverageReport + abstract Builder downloadUri(Optional downloadUri); + + /** Clears the value of downloadUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDownloadUri() { + return downloadUri(Optional.empty()); + } + /** * Setter for state. * @@ -212,42 +313,92 @@ private static Builder create() { @JsonProperty("state") public abstract Builder state(FileState state); + @ExcludeFromGeneratedCoverageReport + abstract Builder state(Optional state); + + /** Clears the value of state field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearState() { + return state(Optional.empty()); + } + + /** + * Setter for state given a known enum. + * + *

    state: Output only. Processing state of the File. + */ @CanIgnoreReturnValue public Builder state(FileState.Known knownType) { return state(new FileState(knownType)); } + /** + * Setter for state given a string. + * + *

    state: Output only. Processing state of the File. + */ @CanIgnoreReturnValue public Builder state(String state) { return state(new FileState(state)); } + /** * Setter for source. * *

    source: Output only. The source of the `File`. */ - @JsonProperty("source") public abstract Builder source(FileSource source); + @ExcludeFromGeneratedCoverageReport + abstract Builder source(Optional source); + + /** Clears the value of source field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSource() { + return source(Optional.empty()); + } + + /** + * Setter for source given a known enum. + * + *

    source: Output only. The source of the `File`. + */ @CanIgnoreReturnValue public Builder source(FileSource.Known knownType) { return source(new FileSource(knownType)); } + /** + * Setter for source given a string. + * + *

    source: Output only. The source of the `File`. + */ @CanIgnoreReturnValue public Builder source(String source) { return source(new FileSource(source)); } + /** * Setter for videoMetadata. * *

    videoMetadata: Output only. Metadata for a video. */ - @JsonProperty("videoMetadata") public abstract Builder videoMetadata(Map videoMetadata); + @ExcludeFromGeneratedCoverageReport + abstract Builder videoMetadata(Optional> videoMetadata); + + /** Clears the value of videoMetadata field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearVideoMetadata() { + return videoMetadata(Optional.empty()); + } + /** * Setter for error. * @@ -261,14 +412,26 @@ public Builder source(String source) { * *

    error: Output only. Error status if File processing failed. */ + @CanIgnoreReturnValue public Builder error(FileStatus.Builder errorBuilder) { return error(errorBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder error(Optional error); + + /** Clears the value of error field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearError() { + return error(Optional.empty()); + } + public abstract File build(); } /** 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..afb386ac60f 100644 --- a/src/main/java/com/google/genai/types/FileData.java +++ b/src/main/java/com/google/genai/types/FileData.java @@ -22,21 +22,27 @@ 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; -/** URI based data. */ +/** + * URI-based data. A FileData message contains a URI pointing to data of a specific media type. It + * is used to represent images, audio, and video stored in Google Cloud Storage. + */ @AutoValue @JsonDeserialize(builder = FileData.Builder.class) 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. + * Optional. The display name of the file. Used to provide a label or filename to distinguish + * files. This field is only returned in `PromptMessage` for prompt management. It is used in the + * Gemini 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. URI. */ + /** Required. The URI of the file in Google Cloud Storage. */ @JsonProperty("fileUri") public abstract Optional fileUri(); @@ -45,6 +51,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(); } @@ -64,20 +71,42 @@ 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. + *

    displayName: Optional. The display name of the file. Used to provide a label or filename + * to distinguish files. This field is only returned in `PromptMessage` for prompt management. + * It is used in the Gemini 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + /** * Setter for fileUri. * - *

    fileUri: Required. URI. + *

    fileUri: Required. The URI of the file in Google Cloud Storage. */ @JsonProperty("fileUri") public abstract Builder fileUri(String fileUri); + @ExcludeFromGeneratedCoverageReport + abstract Builder fileUri(Optional fileUri); + + /** Clears the value of fileUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFileUri() { + return fileUri(Optional.empty()); + } + /** * Setter for mimeType. * @@ -86,10 +115,21 @@ private static Builder create() { @JsonProperty("mimeType") public abstract Builder mimeType(String mimeType); + @ExcludeFromGeneratedCoverageReport + abstract Builder mimeType(Optional mimeType); + + /** Clears the value of mimeType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMimeType() { + return mimeType(Optional.empty()); + } + public abstract FileData build(); } /** 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/FileSearch.java b/src/main/java/com/google/genai/types/FileSearch.java new file mode 100644 index 00000000000..1887e04ba85 --- /dev/null +++ b/src/main/java/com/google/genai/types/FileSearch.java @@ -0,0 +1,147 @@ +/* + * 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; + +/** + * The FileSearch tool that retrieves knowledge from Semantic Retrieval corpora. Files are imported + * to Semantic Retrieval corpora using the ImportFile API. This data type is not supported in Vertex + * AI. + */ +@AutoValue +@JsonDeserialize(builder = FileSearch.Builder.class) +public abstract class FileSearch extends JsonSerializable { + /** + * Required. The names of the file_search_stores to retrieve from. Example: + * `fileSearchStores/my-file-search-store-123` + */ + @JsonProperty("fileSearchStoreNames") + public abstract Optional> fileSearchStoreNames(); + + /** Optional. The number of semantic retrieval chunks to retrieve. */ + @JsonProperty("topK") + public abstract Optional topK(); + + /** Optional. Metadata filter to apply to the semantic retrieval documents and chunks. */ + @JsonProperty("metadataFilter") + public abstract Optional metadataFilter(); + + /** Instantiates a builder for FileSearch. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_FileSearch.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for FileSearch. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `FileSearch.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_FileSearch.Builder(); + } + + /** + * Setter for fileSearchStoreNames. + * + *

    fileSearchStoreNames: Required. The names of the file_search_stores to retrieve from. + * Example: `fileSearchStores/my-file-search-store-123` + */ + @JsonProperty("fileSearchStoreNames") + public abstract Builder fileSearchStoreNames(List fileSearchStoreNames); + + /** + * Setter for fileSearchStoreNames. + * + *

    fileSearchStoreNames: Required. The names of the file_search_stores to retrieve from. + * Example: `fileSearchStores/my-file-search-store-123` + */ + @CanIgnoreReturnValue + public Builder fileSearchStoreNames(String... fileSearchStoreNames) { + return fileSearchStoreNames(Arrays.asList(fileSearchStoreNames)); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder fileSearchStoreNames(Optional> fileSearchStoreNames); + + /** Clears the value of fileSearchStoreNames field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFileSearchStoreNames() { + return fileSearchStoreNames(Optional.empty()); + } + + /** + * Setter for topK. + * + *

    topK: Optional. The number of semantic retrieval chunks to retrieve. + */ + @JsonProperty("topK") + public abstract Builder topK(Integer topK); + + @ExcludeFromGeneratedCoverageReport + abstract Builder topK(Optional topK); + + /** Clears the value of topK field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTopK() { + return topK(Optional.empty()); + } + + /** + * Setter for metadataFilter. + * + *

    metadataFilter: Optional. Metadata filter to apply to the semantic retrieval documents and + * chunks. + */ + @JsonProperty("metadataFilter") + public abstract Builder metadataFilter(String metadataFilter); + + @ExcludeFromGeneratedCoverageReport + abstract Builder metadataFilter(Optional metadataFilter); + + /** Clears the value of metadataFilter field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMetadataFilter() { + return metadataFilter(Optional.empty()); + } + + public abstract FileSearch build(); + } + + /** Deserializes a JSON string to a FileSearch object. */ + @ExcludeFromGeneratedCoverageReport + public static FileSearch fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, FileSearch.class); + } +} diff --git a/src/main/java/com/google/genai/types/FileSearchStore.java b/src/main/java/com/google/genai/types/FileSearchStore.java new file mode 100644 index 00000000000..087dd25a24a --- /dev/null +++ b/src/main/java/com/google/genai/types/FileSearchStore.java @@ -0,0 +1,268 @@ +/* + * 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.time.Instant; +import java.util.Optional; + +/** A collection of Documents. */ +@AutoValue +@JsonDeserialize(builder = FileSearchStore.Builder.class) +public abstract class FileSearchStore extends JsonSerializable { + /** + * The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123` + */ + @JsonProperty("name") + public abstract Optional name(); + + /** The human-readable display name for the FileSearchStore. */ + @JsonProperty("displayName") + public abstract Optional displayName(); + + /** The Timestamp of when the FileSearchStore was created. */ + @JsonProperty("createTime") + public abstract Optional createTime(); + + /** The Timestamp of when the FileSearchStore was last updated. */ + @JsonProperty("updateTime") + public abstract Optional updateTime(); + + /** The number of documents in the FileSearchStore that are active and ready for retrieval. */ + @JsonProperty("activeDocumentsCount") + public abstract Optional activeDocumentsCount(); + + /** The number of documents in the FileSearchStore that are being processed. */ + @JsonProperty("pendingDocumentsCount") + public abstract Optional pendingDocumentsCount(); + + /** The number of documents in the FileSearchStore that have failed processing. */ + @JsonProperty("failedDocumentsCount") + public abstract Optional failedDocumentsCount(); + + /** + * The size of raw bytes ingested into the FileSearchStore. This is the total size of all the + * documents in the FileSearchStore. + */ + @JsonProperty("sizeBytes") + public abstract Optional sizeBytes(); + + /** The embedding model used by the FileSearchStore. */ + @JsonProperty("embeddingModel") + public abstract Optional embeddingModel(); + + /** Instantiates a builder for FileSearchStore. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_FileSearchStore.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for FileSearchStore. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `FileSearchStore.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_FileSearchStore.Builder(); + } + + /** + * Setter for name. + * + *

    name: The resource name of the FileSearchStore. Example: + * `fileSearchStores/my-file-search-store-123` + */ + @JsonProperty("name") + public abstract Builder name(String name); + + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + + /** + * Setter for displayName. + * + *

    displayName: The human-readable display name for the FileSearchStore. + */ + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + + /** + * Setter for createTime. + * + *

    createTime: The Timestamp of when the FileSearchStore was created. + */ + @JsonProperty("createTime") + public abstract Builder createTime(Instant createTime); + + @ExcludeFromGeneratedCoverageReport + abstract Builder createTime(Optional createTime); + + /** Clears the value of createTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCreateTime() { + return createTime(Optional.empty()); + } + + /** + * Setter for updateTime. + * + *

    updateTime: The Timestamp of when the FileSearchStore was last updated. + */ + @JsonProperty("updateTime") + public abstract Builder updateTime(Instant updateTime); + + @ExcludeFromGeneratedCoverageReport + abstract Builder updateTime(Optional updateTime); + + /** Clears the value of updateTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUpdateTime() { + return updateTime(Optional.empty()); + } + + /** + * Setter for activeDocumentsCount. + * + *

    activeDocumentsCount: The number of documents in the FileSearchStore that are active and + * ready for retrieval. + */ + @JsonProperty("activeDocumentsCount") + public abstract Builder activeDocumentsCount(Long activeDocumentsCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder activeDocumentsCount(Optional activeDocumentsCount); + + /** Clears the value of activeDocumentsCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearActiveDocumentsCount() { + return activeDocumentsCount(Optional.empty()); + } + + /** + * Setter for pendingDocumentsCount. + * + *

    pendingDocumentsCount: The number of documents in the FileSearchStore that are being + * processed. + */ + @JsonProperty("pendingDocumentsCount") + public abstract Builder pendingDocumentsCount(Long pendingDocumentsCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder pendingDocumentsCount(Optional pendingDocumentsCount); + + /** Clears the value of pendingDocumentsCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPendingDocumentsCount() { + return pendingDocumentsCount(Optional.empty()); + } + + /** + * Setter for failedDocumentsCount. + * + *

    failedDocumentsCount: The number of documents in the FileSearchStore that have failed + * processing. + */ + @JsonProperty("failedDocumentsCount") + public abstract Builder failedDocumentsCount(Long failedDocumentsCount); + + @ExcludeFromGeneratedCoverageReport + abstract Builder failedDocumentsCount(Optional failedDocumentsCount); + + /** Clears the value of failedDocumentsCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFailedDocumentsCount() { + return failedDocumentsCount(Optional.empty()); + } + + /** + * Setter for sizeBytes. + * + *

    sizeBytes: The size of raw bytes ingested into the FileSearchStore. This is the total size + * of all the documents in the FileSearchStore. + */ + @JsonProperty("sizeBytes") + public abstract Builder sizeBytes(Long sizeBytes); + + @ExcludeFromGeneratedCoverageReport + abstract Builder sizeBytes(Optional sizeBytes); + + /** Clears the value of sizeBytes field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSizeBytes() { + return sizeBytes(Optional.empty()); + } + + /** + * Setter for embeddingModel. + * + *

    embeddingModel: The embedding model used by the FileSearchStore. + */ + @JsonProperty("embeddingModel") + public abstract Builder embeddingModel(String embeddingModel); + + @ExcludeFromGeneratedCoverageReport + abstract Builder embeddingModel(Optional embeddingModel); + + /** Clears the value of embeddingModel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEmbeddingModel() { + return embeddingModel(Optional.empty()); + } + + public abstract FileSearchStore build(); + } + + /** Deserializes a JSON string to a FileSearchStore object. */ + @ExcludeFromGeneratedCoverageReport + public static FileSearchStore fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, FileSearchStore.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..06e9ce1436a 100644 --- a/src/main/java/com/google/genai/types/FileSource.java +++ b/src/main/java/com/google/genai/types/FileSource.java @@ -34,6 +34,8 @@ public enum Known { GENERATED, + REGISTERED, + FILE_SOURCE_UNSPECIFIED } @@ -59,12 +61,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 +95,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.fileSourceEnum != Known.FILE_SOURCE_UNSPECIFIED) { @@ -100,6 +105,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..00729903473 100644 --- a/src/main/java/com/google/genai/types/FileStatus.java +++ b/src/main/java/com/google/genai/types/FileStatus.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.Arrays; import java.util.List; @@ -51,6 +52,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(); } @@ -82,10 +84,21 @@ private static Builder create() { *

    details: A list of messages that carry the error details. There is a common set of message * types for APIs to use. */ + @CanIgnoreReturnValue public Builder details(Map... details) { return details(Arrays.asList(details)); } + @ExcludeFromGeneratedCoverageReport + abstract Builder details(Optional>> details); + + /** Clears the value of details field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDetails() { + return details(Optional.empty()); + } + /** * Setter for message. * @@ -95,6 +108,16 @@ public Builder details(Map... details) { @JsonProperty("message") public abstract Builder message(String message); + @ExcludeFromGeneratedCoverageReport + abstract Builder message(Optional message); + + /** Clears the value of message field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMessage() { + return message(Optional.empty()); + } + /** * Setter for code. * @@ -103,10 +126,21 @@ public Builder details(Map... details) { @JsonProperty("code") public abstract Builder code(Integer code); + @ExcludeFromGeneratedCoverageReport + abstract Builder code(Optional code); + + /** Clears the value of code field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCode() { + return code(Optional.empty()); + } + public abstract FileStatus build(); } /** 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..d4b4e31eb3f 100644 --- a/src/main/java/com/google/genai/types/FinishReason.java +++ b/src/main/java/com/google/genai/types/FinishReason.java @@ -75,7 +75,19 @@ 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, + + /** Image generation stopped because the generated image may be a recitation from a source. */ + IMAGE_RECITATION, + + /** Image generation stopped for a reason not otherwise specified. */ + IMAGE_OTHER } private Known finishReasonEnum; @@ -100,12 +112,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 +146,7 @@ public boolean equals(Object o) { return false; } + @ExcludeFromGeneratedCoverageReport @Override public int hashCode() { if (this.finishReasonEnum != Known.FINISH_REASON_UNSPECIFIED) { @@ -141,6 +156,7 @@ public int hashCode() { } } + @ExcludeFromGeneratedCoverageReport public Known knownEnum() { return this.finishReasonEnum; } diff --git a/src/main/java/com/google/genai/types/FullFineTuningSpec.java b/src/main/java/com/google/genai/types/FullFineTuningSpec.java new file mode 100644 index 00000000000..295cc4604fd --- /dev/null +++ b/src/main/java/com/google/genai/types/FullFineTuningSpec.java @@ -0,0 +1,145 @@ +/* + * 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; + +/** Tuning Spec for Full Fine Tuning. This data type is not supported in Gemini API. */ +@AutoValue +@JsonDeserialize(builder = FullFineTuningSpec.Builder.class) +public abstract class FullFineTuningSpec extends JsonSerializable { + /** Optional. Hyperparameters for Full Fine Tuning. */ + @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 FullFineTuningSpec. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_FullFineTuningSpec.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for FullFineTuningSpec. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `FullFineTuningSpec.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_FullFineTuningSpec.Builder(); + } + + /** + * Setter for hyperParameters. + * + *

    hyperParameters: Optional. Hyperparameters for Full Fine Tuning. + */ + @JsonProperty("hyperParameters") + public abstract Builder hyperParameters(SupervisedHyperParameters hyperParameters); + + /** + * Setter for hyperParameters builder. + * + *

    hyperParameters: Optional. Hyperparameters for Full Fine Tuning. + */ + @CanIgnoreReturnValue + public Builder hyperParameters(SupervisedHyperParameters.Builder hyperParametersBuilder) { + return hyperParameters(hyperParametersBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder hyperParameters(Optional hyperParameters); + + /** Clears the value of hyperParameters field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHyperParameters() { + return hyperParameters(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder trainingDatasetUri(Optional trainingDatasetUri); + + /** Clears the value of trainingDatasetUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTrainingDatasetUri() { + return trainingDatasetUri(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder validationDatasetUri(Optional validationDatasetUri); + + /** Clears the value of validationDatasetUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearValidationDatasetUri() { + return validationDatasetUri(Optional.empty()); + } + + public abstract FullFineTuningSpec build(); + } + + /** Deserializes a JSON string to a FullFineTuningSpec object. */ + @ExcludeFromGeneratedCoverageReport + public static FullFineTuningSpec fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, FullFineTuningSpec.class); + } +} diff --git a/src/main/java/com/google/genai/types/FunctionCall.java b/src/main/java/com/google/genai/types/FunctionCall.java index ca0a88af924..be59f41872e 100644 --- a/src/main/java/com/google/genai/types/FunctionCall.java +++ b/src/main/java/com/google/genai/types/FunctionCall.java @@ -18,11 +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; @@ -44,11 +49,26 @@ public abstract class FunctionCall extends JsonSerializable { @JsonProperty("args") public abstract Optional> args(); - /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + /** Optional. The name of the function to call. Matches [FunctionDeclaration.name]. */ @JsonProperty("name") public abstract Optional name(); + /** + * Optional. The partial argument value of the function call. If provided, represents the + * arguments/fields that are streamed incrementally. This field is not supported in Gemini API. + */ + @JsonProperty("partialArgs") + public abstract Optional> partialArgs(); + + /** + * Optional. Whether this is the last part of the FunctionCall. If true, another partial message + * for the current FunctionCall is expected to follow. This field is not supported in Gemini API. + */ + @JsonProperty("willContinue") + public abstract Optional willContinue(); + /** Instantiates a builder for FunctionCall. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_FunctionCall.Builder(); } @@ -74,6 +94,16 @@ private static Builder create() { @JsonProperty("id") public abstract Builder id(String id); + @ExcludeFromGeneratedCoverageReport + abstract Builder id(Optional id); + + /** Clears the value of id field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearId() { + return id(Optional.empty()); + } + /** * Setter for args. * @@ -83,18 +113,106 @@ private static Builder create() { @JsonProperty("args") public abstract Builder args(Map args); + @ExcludeFromGeneratedCoverageReport + abstract Builder args(Optional> args); + + /** Clears the value of args field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearArgs() { + return args(Optional.empty()); + } + /** * Setter for name. * - *

    name: Required. The name of the function to call. Matches [FunctionDeclaration.name]. + *

    name: Optional. The name of the function to call. Matches [FunctionDeclaration.name]. */ @JsonProperty("name") public abstract Builder name(String name); + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + + /** + * Setter for partialArgs. + * + *

    partialArgs: Optional. The partial argument value of the function call. If provided, + * represents the arguments/fields that are streamed incrementally. This field is not supported + * in Gemini API. + */ + @JsonProperty("partialArgs") + public abstract Builder partialArgs(List partialArgs); + + /** + * Setter for partialArgs. + * + *

    partialArgs: Optional. The partial argument value of the function call. If provided, + * represents the arguments/fields that are streamed incrementally. This field is not supported + * in Gemini API. + */ + @CanIgnoreReturnValue + public Builder partialArgs(PartialArg... partialArgs) { + return partialArgs(Arrays.asList(partialArgs)); + } + + /** + * Setter for partialArgs builder. + * + *

    partialArgs: Optional. The partial argument value of the function call. If provided, + * represents the arguments/fields that are streamed incrementally. This field is not supported + * in Gemini API. + */ + @CanIgnoreReturnValue + public Builder partialArgs(PartialArg.Builder... partialArgsBuilders) { + return partialArgs( + Arrays.asList(partialArgsBuilders).stream() + .map(PartialArg.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder partialArgs(Optional> partialArgs); + + /** Clears the value of partialArgs field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPartialArgs() { + return partialArgs(Optional.empty()); + } + + /** + * Setter for willContinue. + * + *

    willContinue: Optional. Whether this is the last part of the FunctionCall. If true, + * another partial message for the current FunctionCall is expected to follow. This field is not + * supported in Gemini API. + */ + @JsonProperty("willContinue") + public abstract Builder willContinue(boolean willContinue); + + @ExcludeFromGeneratedCoverageReport + abstract Builder willContinue(Optional willContinue); + + /** Clears the value of willContinue field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearWillContinue() { + return willContinue(Optional.empty()); + } + public abstract FunctionCall build(); } /** 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 8fc1775ed18..f5b59242c95 100644 --- a/src/main/java/com/google/genai/types/FunctionCallingConfig.java +++ b/src/main/java/com/google/genai/types/FunctionCallingConfig.java @@ -32,10 +32,6 @@ @AutoValue @JsonDeserialize(builder = FunctionCallingConfig.Builder.class) public abstract class FunctionCallingConfig extends JsonSerializable { - /** Optional. Function calling mode. */ - @JsonProperty("mode") - public abstract Optional mode(); - /** * Optional. Function names to call. Only set when the Mode is ANY. Function names should match * [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the @@ -44,7 +40,20 @@ public abstract class FunctionCallingConfig extends JsonSerializable { @JsonProperty("allowedFunctionNames") public abstract Optional> allowedFunctionNames(); + /** Optional. Function calling mode. */ + @JsonProperty("mode") + public abstract Optional mode(); + + /** + * Optional. When set to true, arguments of a single function call will be streamed out in + * multiple parts/contents/responses. Partial parameter results will be returned in the + * [FunctionCall.partial_args] field. This field is not supported in Gemini API. + */ + @JsonProperty("streamFunctionCallArguments") + public abstract Optional streamFunctionCallArguments(); + /** Instantiates a builder for FunctionCallingConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_FunctionCallingConfig.Builder(); } @@ -61,6 +70,38 @@ private static Builder create() { return new AutoValue_FunctionCallingConfig.Builder(); } + /** + * Setter for allowedFunctionNames. + * + *

    allowedFunctionNames: Optional. Function names to call. Only set when the Mode is ANY. + * Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will + * predict a function call from the set of function names provided. + */ + @JsonProperty("allowedFunctionNames") + public abstract Builder allowedFunctionNames(List allowedFunctionNames); + + /** + * Setter for allowedFunctionNames. + * + *

    allowedFunctionNames: Optional. Function names to call. Only set when the Mode is ANY. + * Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will + * predict a function call from the set of function names provided. + */ + @CanIgnoreReturnValue + public Builder allowedFunctionNames(String... allowedFunctionNames) { + return allowedFunctionNames(Arrays.asList(allowedFunctionNames)); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder allowedFunctionNames(Optional> allowedFunctionNames); + + /** Clears the value of allowedFunctionNames field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAllowedFunctionNames() { + return allowedFunctionNames(Optional.empty()); + } + /** * Setter for mode. * @@ -69,41 +110,62 @@ private static Builder create() { @JsonProperty("mode") public abstract Builder mode(FunctionCallingConfigMode mode); + @ExcludeFromGeneratedCoverageReport + abstract Builder mode(Optional mode); + + /** Clears the value of mode field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMode() { + return mode(Optional.empty()); + } + + /** + * Setter for mode given a known enum. + * + *

    mode: Optional. Function calling mode. + */ @CanIgnoreReturnValue public Builder mode(FunctionCallingConfigMode.Known knownType) { return mode(new FunctionCallingConfigMode(knownType)); } + /** + * Setter for mode given a string. + * + *

    mode: Optional. Function calling mode. + */ @CanIgnoreReturnValue public Builder mode(String mode) { return mode(new FunctionCallingConfigMode(mode)); } + /** - * Setter for allowedFunctionNames. + * Setter for streamFunctionCallArguments. * - *

    allowedFunctionNames: Optional. Function names to call. Only set when the Mode is ANY. - * Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will - * predict a function call from the set of function names provided. + *

    streamFunctionCallArguments: Optional. When set to true, arguments of a single function + * call will be streamed out in multiple parts/contents/responses. Partial parameter results + * will be returned in the [FunctionCall.partial_args] field. This field is not supported in + * Gemini API. */ + @JsonProperty("streamFunctionCallArguments") + public abstract Builder streamFunctionCallArguments(boolean streamFunctionCallArguments); - @JsonProperty("allowedFunctionNames") - public abstract Builder allowedFunctionNames(List allowedFunctionNames); + @ExcludeFromGeneratedCoverageReport + abstract Builder streamFunctionCallArguments(Optional streamFunctionCallArguments); - /** - * Setter for allowedFunctionNames. - * - *

    allowedFunctionNames: Optional. Function names to call. Only set when the Mode is ANY. - * Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will - * predict a function call from the set of function names provided. - */ - public Builder allowedFunctionNames(String... allowedFunctionNames) { - return allowedFunctionNames(Arrays.asList(allowedFunctionNames)); + /** Clears the value of streamFunctionCallArguments field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearStreamFunctionCallArguments() { + return streamFunctionCallArguments(Optional.empty()); } public abstract FunctionCallingConfig build(); } /** 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..f3ce4c61ed2 100644 --- a/src/main/java/com/google/genai/types/FunctionCallingConfigMode.java +++ b/src/main/java/com/google/genai/types/FunctionCallingConfigMode.java @@ -23,12 +23,12 @@ import com.google.common.base.Ascii; import java.util.Objects; -/** Config for the function calling config mode. */ +/** Function calling mode. */ public class FunctionCallingConfigMode { /** Enum representing the known values for FunctionCallingConfigMode. */ public enum Known { - /** The function calling config mode is unspecified. Should not be used. */ + /** Unspecified function calling mode. This value should not be used. */ MODE_UNSPECIFIED, /** @@ -50,6 +50,14 @@ public enum Known { */ NONE, + /** + * Model is constrained to predict either function calls or natural language response. If + * "allowed_function_names" are set, the predicted function calls will be limited to any one of + * "allowed_function_names", else the predicted function calls 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 65ad4ffcc10..bd9e3c5f3ef 100644 --- a/src/main/java/com/google/genai/types/FunctionDeclaration.java +++ b/src/main/java/com/google/genai/types/FunctionDeclaration.java @@ -27,6 +27,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -34,17 +36,15 @@ import java.util.Optional; /** - * Defines a function that the model can generate JSON inputs for. - * - *

    The inputs are based on `OpenAPI 3.0 specifications `_. + * Structured representation of a function declaration as defined by the [OpenAPI 3.0 + * specification](https://spec.openapis.org/oas/v3.0.3). Included in this declaration are the + * function name, description, parameters and response type. This FunctionDeclaration is a + * representation of a block of code that can be used as a `Tool` by the model and executed by the + * client. */ @AutoValue @JsonDeserialize(builder = FunctionDeclaration.Builder.class) public abstract class FunctionDeclaration extends JsonSerializable { - /** Defines the function behavior. */ - @JsonProperty("behavior") - public abstract Optional behavior(); - /** * Optional. Description and purpose of the function. Model uses it to decide how and whether to * call the function. @@ -54,7 +54,7 @@ public abstract class FunctionDeclaration extends JsonSerializable { /** * Required. The name of the function to call. Must start with a letter or an underscore. Must be - * a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. + * a-z, A-Z, 0-9, or contain underscores, dots, colons and dashes, with a maximum length of 64. */ @JsonProperty("name") public abstract Optional name(); @@ -71,6 +71,16 @@ public abstract class FunctionDeclaration extends JsonSerializable { @JsonProperty("parameters") public abstract Optional parameters(); + /** + * Optional. Describes the parameters to the function in JSON Schema format. The schema must + * describe an object where the properties are the parameters to the function. For example: ``` { + * "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, + * "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] + * } ``` This field is mutually exclusive with `parameters`. + */ + @JsonProperty("parametersJsonSchema") + public abstract Optional parametersJsonSchema(); + /** * Optional. Describes the output from this function in JSON Schema format. Reflects the Open API * 3.03 Response Object. The Schema defines the type used for the response value of the function. @@ -78,7 +88,24 @@ public abstract class FunctionDeclaration extends JsonSerializable { @JsonProperty("response") public abstract Optional response(); + /** + * Optional. Describes the output from this function in JSON Schema format. The value specified by + * the schema is the response value of the function. This field is mutually exclusive with + * `response`. + */ + @JsonProperty("responseJsonSchema") + public abstract Optional responseJsonSchema(); + + /** + * Optional. Specifies the function Behavior. Currently only non-blocking functions are supported. + * If not specified, the system keeps the current function call behavior. This field is currently + * only supported by the BidiGenerateContent method. + */ + @JsonProperty("behavior") + public abstract Optional behavior(); + /** Instantiates a builder for FunctionDeclaration. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_FunctionDeclaration.Builder(); } @@ -95,43 +122,45 @@ private static Builder create() { return new AutoValue_FunctionDeclaration.Builder(); } - /** - * Setter for behavior. - * - *

    behavior: Defines the function behavior. - */ - @JsonProperty("behavior") - public abstract Builder behavior(Behavior behavior); - - @CanIgnoreReturnValue - public Builder behavior(Behavior.Known knownType) { - return behavior(new Behavior(knownType)); - } - - @CanIgnoreReturnValue - public Builder behavior(String behavior) { - return behavior(new Behavior(behavior)); - } /** * Setter for description. * *

    description: Optional. Description and purpose of the function. Model uses it to decide * how and whether to call the function. */ - @JsonProperty("description") public abstract Builder description(String description); + @ExcludeFromGeneratedCoverageReport + abstract Builder description(Optional description); + + /** Clears the value of description field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDescription() { + return description(Optional.empty()); + } + /** * Setter for name. * *

    name: Required. The name of the function to call. Must start with a letter or an - * underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum - * length of 64. + * underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots, colons and dashes, with a + * maximum length of 64. */ @JsonProperty("name") public abstract Builder name(String name); + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + /** * Setter for parameters. * @@ -157,10 +186,43 @@ public Builder behavior(String behavior) { * underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: * type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + @CanIgnoreReturnValue public Builder parameters(Schema.Builder parametersBuilder) { return parameters(parametersBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder parameters(Optional parameters); + + /** Clears the value of parameters field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearParameters() { + return parameters(Optional.empty()); + } + + /** + * Setter for parametersJsonSchema. + * + *

    parametersJsonSchema: Optional. Describes the parameters to the function in JSON Schema + * format. The schema must describe an object where the properties are the parameters to the + * function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, + * "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], + * "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`. + */ + @JsonProperty("parametersJsonSchema") + public abstract Builder parametersJsonSchema(Object parametersJsonSchema); + + @ExcludeFromGeneratedCoverageReport + abstract Builder parametersJsonSchema(Optional parametersJsonSchema); + + /** Clears the value of parametersJsonSchema field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearParametersJsonSchema() { + return parametersJsonSchema(Optional.empty()); + } + /** * Setter for response. * @@ -178,14 +240,90 @@ public Builder parameters(Schema.Builder parametersBuilder) { * Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response * value of the function. */ + @CanIgnoreReturnValue public Builder response(Schema.Builder responseBuilder) { return response(responseBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder response(Optional response); + + /** Clears the value of response field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResponse() { + return response(Optional.empty()); + } + + /** + * Setter for responseJsonSchema. + * + *

    responseJsonSchema: Optional. Describes the output from this function in JSON Schema + * format. The value specified by the schema is the response value of the function. This field + * is mutually exclusive with `response`. + */ + @JsonProperty("responseJsonSchema") + public abstract Builder responseJsonSchema(Object responseJsonSchema); + + @ExcludeFromGeneratedCoverageReport + abstract Builder responseJsonSchema(Optional responseJsonSchema); + + /** Clears the value of responseJsonSchema field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResponseJsonSchema() { + return responseJsonSchema(Optional.empty()); + } + + /** + * Setter for behavior. + * + *

    behavior: Optional. Specifies the function Behavior. Currently only non-blocking functions + * are supported. If not specified, the system keeps the current function call behavior. This + * field is currently only supported by the BidiGenerateContent method. + */ + @JsonProperty("behavior") + public abstract Builder behavior(Behavior behavior); + + @ExcludeFromGeneratedCoverageReport + abstract Builder behavior(Optional behavior); + + /** Clears the value of behavior field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBehavior() { + return behavior(Optional.empty()); + } + + /** + * Setter for behavior given a known enum. + * + *

    behavior: Optional. Specifies the function Behavior. Currently only non-blocking functions + * are supported. If not specified, the system keeps the current function call behavior. This + * field is currently only supported by the BidiGenerateContent method. + */ + @CanIgnoreReturnValue + public Builder behavior(Behavior.Known knownType) { + return behavior(new Behavior(knownType)); + } + + /** + * Setter for behavior given a string. + * + *

    behavior: Optional. Specifies the function Behavior. Currently only non-blocking functions + * are supported. If not specified, the system keeps the current function call behavior. This + * field is currently only supported by the BidiGenerateContent method. + */ + @CanIgnoreReturnValue + public Builder behavior(String behavior) { + return behavior(new Behavior(behavior)); + } + public abstract FunctionDeclaration build(); } /** Deserializes a JSON string to a FunctionDeclaration object. */ + @ExcludeFromGeneratedCoverageReport public static FunctionDeclaration fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, FunctionDeclaration.class); } @@ -245,57 +383,84 @@ public static FunctionDeclaration fromMethod( } else { parameterName = orderedParameterNames[i]; } - properties.put(parameterName, buildTypeSchema(parameterName, parameters[i].getType())); + properties.put( + parameterName, + buildTypeSchema(parameterName, parameters[i].getParameterizedType(), "parameter ")); required.add(parameterName); } parametersBuilder.properties(properties).required(required); + Schema responseSchema; + try { + responseSchema = buildTypeSchema("return type", method.getReturnType(), ""); + } catch (IllegalArgumentException e) { + + responseSchema = Schema.builder().title("return type").type("OBJECT").build(); + } + return FunctionDeclaration.builder() .name(method.getName()) .description(functionDescription) .parameters(parametersBuilder.build()) + .response(responseSchema) .build(); } /** - * Builds a Schema object for a given parameter name and type. + * Builds a Schema object for a parameter or return type given its name and type. * - * @param parameterName The name of the parameter. - * @param parameterType The type of the parameter as a Class object. + * @param name The name of the parameter or return type. + * @param type The type of the parameter or return type as a Type object. + * @param prefix The prefix to add to the error message. * @return A Schema object representing the parameter's type and metadata. * @throws IllegalArgumentException If the parameter type is unsupported. */ - private static Schema buildTypeSchema(String parameterName, Class parameterType) { - Schema.Builder parameterSchemaBuilder = Schema.builder().title(parameterName); - - switch (parameterType.getName()) { - case "java.lang.String": - parameterSchemaBuilder = parameterSchemaBuilder.type("STRING"); - break; - case "boolean": - case "java.lang.Boolean": - parameterSchemaBuilder = parameterSchemaBuilder.type("BOOLEAN"); - break; - case "int": - case "java.lang.Integer": - case "java.lang.Long": - parameterSchemaBuilder = parameterSchemaBuilder.type("INTEGER"); - break; - case "double": - case "java.lang.Double": - case "float": - case "java.lang.Float": - parameterSchemaBuilder = parameterSchemaBuilder.type("NUMBER"); - break; - default: + private static Schema buildTypeSchema(String name, Type type, String prefix) { + String errorMessage = + "Unsupported type %s for %s%s. Currently, supported types are String, boolean, Boolean," + + " int, Integer, Long, double, Double, float, Float, and List."; + Schema.Builder schemaBuilder = Schema.builder().title(name); + + String typeName = type.getTypeName(); + + if (type instanceof Class) { + Class parameterClass = (Class) type; + typeName = parameterClass.getName(); + switch (typeName) { + case "java.lang.String": + schemaBuilder = schemaBuilder.type("STRING"); + break; + case "boolean": + case "java.lang.Boolean": + schemaBuilder = schemaBuilder.type("BOOLEAN"); + break; + case "int": + case "java.lang.Integer": + case "java.lang.Long": + schemaBuilder = schemaBuilder.type("INTEGER"); + break; + case "double": + case "java.lang.Double": + case "float": + case "java.lang.Float": + schemaBuilder = schemaBuilder.type("NUMBER"); + break; + default: + throw new IllegalArgumentException(String.format(errorMessage, typeName, prefix, name)); + } + } else if (type instanceof ParameterizedType) { + ParameterizedType pType = (ParameterizedType) type; + if (pType.getRawType().equals(List.class)) { + Type itemType = pType.getActualTypeArguments()[0]; + Schema itemSchema = buildTypeSchema(name + "Item", itemType, prefix); + schemaBuilder.type("ARRAY").items(itemSchema); + } else { throw new IllegalArgumentException( - "Unsupported parameter type " - + parameterType.getName() - + " for parameter " - + parameterName - + ". Currently, supported types are String, boolean, Boolean, int, Integer, Long," - + " double, Double, float, Float."); + String.format(errorMessage, pType.getRawType().getTypeName(), prefix + "item ", name)); + } + } else { + throw new IllegalArgumentException(String.format(errorMessage, typeName, prefix, name)); } - return parameterSchemaBuilder.build(); + return schemaBuilder.build(); } } diff --git a/src/main/java/com/google/genai/types/FunctionResponse.java b/src/main/java/com/google/genai/types/FunctionResponse.java index 6cbe6aafc14..caf7fbd4ace 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(); } @@ -102,6 +114,16 @@ private static Builder create() { @JsonProperty("willContinue") public abstract Builder willContinue(boolean willContinue); + @ExcludeFromGeneratedCoverageReport + abstract Builder willContinue(Optional willContinue); + + /** Clears the value of willContinue field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearWillContinue() { + return willContinue(Optional.empty()); + } + /** * Setter for scheduling. * @@ -111,25 +133,101 @@ private static Builder create() { @JsonProperty("scheduling") public abstract Builder scheduling(FunctionResponseScheduling scheduling); + @ExcludeFromGeneratedCoverageReport + abstract Builder scheduling(Optional scheduling); + + /** Clears the value of scheduling field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearScheduling() { + return scheduling(Optional.empty()); + } + + /** + * Setter for scheduling given a known enum. + * + *

    scheduling: Specifies how the response should be scheduled in the conversation. Only + * applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. + */ @CanIgnoreReturnValue public Builder scheduling(FunctionResponseScheduling.Known knownType) { return scheduling(new FunctionResponseScheduling(knownType)); } + /** + * Setter for scheduling given a string. + * + *

    scheduling: Specifies how the response should be scheduled in the conversation. Only + * applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. + */ @CanIgnoreReturnValue 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. + */ + @CanIgnoreReturnValue + 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. + */ + @CanIgnoreReturnValue + public Builder parts(FunctionResponsePart.Builder... partsBuilders) { + return parts( + Arrays.asList(partsBuilders).stream() + .map(FunctionResponsePart.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder parts(Optional> parts); + + /** Clears the value of parts field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearParts() { + return parts(Optional.empty()); + } + /** * Setter for id. * *

    id: Optional. The id of the function call this response is for. Populated by the client to * match the corresponding function call `id`. */ - @JsonProperty("id") public abstract Builder id(String id); + @ExcludeFromGeneratedCoverageReport + abstract Builder id(Optional id); + + /** Clears the value of id field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearId() { + return id(Optional.empty()); + } + /** * Setter for name. * @@ -139,6 +237,16 @@ public Builder scheduling(String scheduling) { @JsonProperty("name") public abstract Builder name(String name); + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + /** * Setter for response. * @@ -149,10 +257,21 @@ public Builder scheduling(String scheduling) { @JsonProperty("response") public abstract Builder response(Map response); + @ExcludeFromGeneratedCoverageReport + abstract Builder response(Optional> response); + + /** Clears the value of response field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResponse() { + return response(Optional.empty()); + } + public abstract FunctionResponse build(); } /** 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..c16c6c50547 --- /dev/null +++ b/src/main/java/com/google/genai/types/FunctionResponseBlob.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 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; + +/** + * 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(); + + /** + * Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. + */ + @JsonProperty("displayName") + public abstract Optional displayName(); + + /** 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder mimeType(Optional mimeType); + + /** Clears the value of mimeType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMimeType() { + return mimeType(Optional.empty()); + } + + /** + * Setter for data. + * + *

    data: Required. Inline media bytes. + */ + @JsonProperty("data") + public abstract Builder data(byte[] data); + + @ExcludeFromGeneratedCoverageReport + abstract Builder data(Optional data); + + /** Clears the value of data field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearData() { + return data(Optional.empty()); + } + + /** + * Setter for displayName. + * + *

    displayName: Optional. Display name of the blob. Used to provide a label or filename to + * distinguish blobs. + */ + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + + 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..863264c9e4c --- /dev/null +++ b/src/main/java/com/google/genai/types/FunctionResponseFileData.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 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; + +/** 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(); + + /** + * Optional. Display name of the file. Used to provide a label or filename to distinguish files. + */ + @JsonProperty("displayName") + public abstract Optional displayName(); + + /** 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder fileUri(Optional fileUri); + + /** Clears the value of fileUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFileUri() { + return fileUri(Optional.empty()); + } + + /** + * Setter for mimeType. + * + *

    mimeType: Required. The IANA standard MIME type of the source data. + */ + @JsonProperty("mimeType") + public abstract Builder mimeType(String mimeType); + + @ExcludeFromGeneratedCoverageReport + abstract Builder mimeType(Optional mimeType); + + /** Clears the value of mimeType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMimeType() { + return mimeType(Optional.empty()); + } + + /** + * Setter for displayName. + * + *

    displayName: Optional. Display name of the file. Used to provide a label or filename to + * distinguish files. + */ + @JsonProperty("displayName") + public abstract Builder displayName(String displayName); + + @ExcludeFromGeneratedCoverageReport + abstract Builder displayName(Optional displayName); + + /** Clears the value of displayName field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDisplayName() { + return displayName(Optional.empty()); + } + + 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..cd7f0437dd5 --- /dev/null +++ b/src/main/java/com/google/genai/types/FunctionResponsePart.java @@ -0,0 +1,149 @@ +/* + * 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 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. + */ + @CanIgnoreReturnValue + public Builder inlineData(FunctionResponseBlob.Builder inlineDataBuilder) { + return inlineData(inlineDataBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder inlineData(Optional inlineData); + + /** Clears the value of inlineData field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearInlineData() { + return inlineData(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder fileData(FunctionResponseFileData.Builder fileDataBuilder) { + return fileData(fileDataBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder fileData(Optional fileData); + + /** Clears the value of fileData field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFileData() { + return fileData(Optional.empty()); + } + + 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/GcsDestination.java b/src/main/java/com/google/genai/types/GcsDestination.java new file mode 100644 index 00000000000..8c0acbfb8b1 --- /dev/null +++ b/src/main/java/com/google/genai/types/GcsDestination.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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Optional; + +/** The Google Cloud Storage location where the output is to be written to. */ +@AutoValue +@JsonDeserialize(builder = GcsDestination.Builder.class) +public abstract class GcsDestination extends JsonSerializable { + /** + * Required. Google Cloud Storage URI to output directory. If the uri doesn't end with '/', a '/' + * will be automatically appended. The directory is created if it doesn't exist. + */ + @JsonProperty("outputUriPrefix") + public abstract Optional outputUriPrefix(); + + /** Instantiates a builder for GcsDestination. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_GcsDestination.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for GcsDestination. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `GcsDestination.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_GcsDestination.Builder(); + } + + /** + * Setter for outputUriPrefix. + * + *

    outputUriPrefix: Required. Google Cloud Storage URI to output directory. If the uri + * doesn't end with '/', a '/' will be automatically appended. The directory is created if it + * doesn't exist. + */ + @JsonProperty("outputUriPrefix") + public abstract Builder outputUriPrefix(String outputUriPrefix); + + @ExcludeFromGeneratedCoverageReport + abstract Builder outputUriPrefix(Optional outputUriPrefix); + + /** Clears the value of outputUriPrefix field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputUriPrefix() { + return outputUriPrefix(Optional.empty()); + } + + public abstract GcsDestination build(); + } + + /** Deserializes a JSON string to a GcsDestination object. */ + @ExcludeFromGeneratedCoverageReport + public static GcsDestination fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, GcsDestination.class); + } +} diff --git a/src/main/java/com/google/genai/types/GcsSource.java b/src/main/java/com/google/genai/types/GcsSource.java new file mode 100644 index 00000000000..818d548b6c5 --- /dev/null +++ b/src/main/java/com/google/genai/types/GcsSource.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.errorprone.annotations.CanIgnoreReturnValue; +import com.google.genai.JsonSerializable; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** + * The Google Cloud Storage location for the input content. This data type is not supported in + * Gemini API. + */ +@AutoValue +@JsonDeserialize(builder = GcsSource.Builder.class) +public abstract class GcsSource extends JsonSerializable { + /** + * Required. Google Cloud Storage URI(-s) to the input file(s). May contain wildcards. For more + * information on wildcards, see https://cloud.google.com/storage/docs/wildcards. + */ + @JsonProperty("uris") + public abstract Optional> uris(); + + /** Instantiates a builder for GcsSource. */ + @ExcludeFromGeneratedCoverageReport + public static Builder builder() { + return new AutoValue_GcsSource.Builder(); + } + + /** Creates a builder with the same values as this instance. */ + public abstract Builder toBuilder(); + + /** Builder for GcsSource. */ + @AutoValue.Builder + public abstract static class Builder { + /** For internal usage. Please use `GcsSource.builder()` for instantiation. */ + @JsonCreator + private static Builder create() { + return new AutoValue_GcsSource.Builder(); + } + + /** + * Setter for uris. + * + *

    uris: Required. Google Cloud Storage URI(-s) to the input file(s). May contain wildcards. + * For more information on wildcards, see https://cloud.google.com/storage/docs/wildcards. + */ + @JsonProperty("uris") + public abstract Builder uris(List uris); + + /** + * Setter for uris. + * + *

    uris: Required. Google Cloud Storage URI(-s) to the input file(s). May contain wildcards. + * For more information on wildcards, see https://cloud.google.com/storage/docs/wildcards. + */ + @CanIgnoreReturnValue + public Builder uris(String... uris) { + return uris(Arrays.asList(uris)); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder uris(Optional> uris); + + /** Clears the value of uris field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUris() { + return uris(Optional.empty()); + } + + public abstract GcsSource build(); + } + + /** Deserializes a JSON string to a GcsSource object. */ + @ExcludeFromGeneratedCoverageReport + public static GcsSource fromJson(String jsonString) { + return JsonSerializable.fromJsonString(jsonString, GcsSource.class); + } +} 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..b83df735e44 --- /dev/null +++ b/src/main/java/com/google/genai/types/GeminiPreferenceExample.java @@ -0,0 +1,153 @@ +/* + * 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.errorprone.annotations.CanIgnoreReturnValue; +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. + */ + @CanIgnoreReturnValue + public Builder completions(GeminiPreferenceExampleCompletion... completions) { + return completions(Arrays.asList(completions)); + } + + /** + * Setter for completions builder. + * + *

    completions: List of completions for a given prompt. + */ + @CanIgnoreReturnValue + public Builder completions(GeminiPreferenceExampleCompletion.Builder... completionsBuilders) { + return completions( + Arrays.asList(completionsBuilders).stream() + .map(GeminiPreferenceExampleCompletion.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder completions(Optional> completions); + + /** Clears the value of completions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCompletions() { + return completions(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder contents(Content... contents) { + return contents(Arrays.asList(contents)); + } + + /** + * Setter for contents builder. + * + *

    contents: Multi-turn contents that represents the Prompt. + */ + @CanIgnoreReturnValue + public Builder contents(Content.Builder... contentsBuilders) { + return contents( + Arrays.asList(contentsBuilders).stream() + .map(Content.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder contents(Optional> contents); + + /** Clears the value of contents field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearContents() { + return contents(Optional.empty()); + } + + 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..7780ab52c9f --- /dev/null +++ b/src/main/java/com/google/genai/types/GeminiPreferenceExampleCompletion.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 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; + +/** 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. + */ + @CanIgnoreReturnValue + public Builder completion(Content.Builder completionBuilder) { + return completion(completionBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder completion(Optional completion); + + /** Clears the value of completion field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCompletion() { + return completion(Optional.empty()); + } + + /** + * Setter for score. + * + *

    score: The score for the given completion. + */ + @JsonProperty("score") + public abstract Builder score(Float score); + + @ExcludeFromGeneratedCoverageReport + abstract Builder score(Optional score); + + /** Clears the value of score field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearScore() { + return score(Optional.empty()); + } + + 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 18201beb2f5..84fc4fa02c5 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". @@ -127,7 +131,6 @@ public abstract class GenerateContentConfig extends JsonSerializable { * Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: * (default) Text output. - `application/json`: JSON response in the candidates. The model needs * to be prompted to output the appropriate response type, otherwise the behavior is undefined. - * This is a preview feature. */ @JsonProperty("responseMimeType") public abstract Optional responseMimeType(); @@ -137,10 +140,29 @@ public abstract class GenerateContentConfig extends JsonSerializable { * objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema * object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type * must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. + * + *

    If `response_schema` doesn't process your schema correctly, try using `response_json_schema` + * instead. */ @JsonProperty("responseSchema") public abstract Optional responseSchema(); + /** + * Optional. Output schema of the generated response. This is an alternative to `response_schema` + * that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be + * omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all + * features are supported. Specifically, only the following properties are supported: - `$id` - + * `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for + * strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + * `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - + * `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be + * set. Cyclic references are unrolled to a limited degree and, as such, may only be used within + * non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a + * sub-schema, no other properties, except for than those starting as a `$`, may be set. + */ + @JsonProperty("responseJsonSchema") + public abstract Optional responseJsonSchema(); + /** Configuration for model router requests. */ @JsonProperty("routingConfig") public abstract Optional routingConfig(); @@ -199,7 +221,30 @@ public abstract class GenerateContentConfig extends JsonSerializable { @JsonProperty("thinkingConfig") public abstract Optional thinkingConfig(); + /** The image generation configuration. */ + @JsonProperty("imageConfig") + public abstract Optional imageConfig(); + + /** + * Enables enhanced civic answers. It may not be available for all models. This field is not + * supported in Gemini Enterprise Agent Platform. + */ + @JsonProperty("enableEnhancedCivicAnswers") + public abstract Optional enableEnhancedCivicAnswers(); + + /** + * Settings for prompt and response sanitization using the Model Armor service. If supplied, + * safety_settings must not be supplied. + */ + @JsonProperty("modelArmorConfig") + public abstract Optional modelArmorConfig(); + + /** The service tier to use for the request. For example, ServiceTier.FLEX. */ + @JsonProperty("serviceTier") + public abstract Optional serviceTier(); + /** Instantiates a builder for GenerateContentConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateContentConfig.Builder(); } @@ -229,10 +274,40 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder shouldReturnHttpResponse(Optional shouldReturnHttpResponse); + + /** Clears the value of shouldReturnHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearShouldReturnHttpResponse() { + return shouldReturnHttpResponse(Optional.empty()); + } + /** * Setter for systemInstruction. * @@ -248,10 +323,21 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { *

    systemInstruction: 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". */ + @CanIgnoreReturnValue public Builder systemInstruction(Content.Builder systemInstructionBuilder) { return systemInstruction(systemInstructionBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder systemInstruction(Optional systemInstruction); + + /** Clears the value of systemInstruction field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSystemInstruction() { + return systemInstruction(Optional.empty()); + } + /** * Setter for temperature. * @@ -262,6 +348,16 @@ public Builder systemInstruction(Content.Builder systemInstructionBuilder) { @JsonProperty("temperature") public abstract Builder temperature(Float temperature); + @ExcludeFromGeneratedCoverageReport + abstract Builder temperature(Optional temperature); + + /** Clears the value of temperature field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTemperature() { + return temperature(Optional.empty()); + } + /** * Setter for topP. * @@ -272,6 +368,16 @@ public Builder systemInstruction(Content.Builder systemInstructionBuilder) { @JsonProperty("topP") public abstract Builder topP(Float topP); + @ExcludeFromGeneratedCoverageReport + abstract Builder topP(Optional topP); + + /** Clears the value of topP field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTopP() { + return topP(Optional.empty()); + } + /** * Setter for topK. * @@ -283,6 +389,16 @@ public Builder systemInstruction(Content.Builder systemInstructionBuilder) { @JsonProperty("topK") public abstract Builder topK(Float topK); + @ExcludeFromGeneratedCoverageReport + abstract Builder topK(Optional topK); + + /** Clears the value of topK field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTopK() { + return topK(Optional.empty()); + } + /** * Setter for candidateCount. * @@ -291,6 +407,16 @@ public Builder systemInstruction(Content.Builder systemInstructionBuilder) { @JsonProperty("candidateCount") public abstract Builder candidateCount(Integer candidateCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder candidateCount(Optional candidateCount); + + /** Clears the value of candidateCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCandidateCount() { + return candidateCount(Optional.empty()); + } + /** * Setter for maxOutputTokens. * @@ -299,6 +425,16 @@ public Builder systemInstruction(Content.Builder systemInstructionBuilder) { @JsonProperty("maxOutputTokens") public abstract Builder maxOutputTokens(Integer maxOutputTokens); + @ExcludeFromGeneratedCoverageReport + abstract Builder maxOutputTokens(Optional maxOutputTokens); + + /** Clears the value of maxOutputTokens field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMaxOutputTokens() { + return maxOutputTokens(Optional.empty()); + } + /** * Setter for stopSequences. * @@ -314,10 +450,21 @@ public Builder systemInstruction(Content.Builder systemInstructionBuilder) { *

    stopSequences: List of strings that tells the model to stop generating text if one of the * strings is encountered in the response. */ + @CanIgnoreReturnValue public Builder stopSequences(String... stopSequences) { return stopSequences(Arrays.asList(stopSequences)); } + @ExcludeFromGeneratedCoverageReport + abstract Builder stopSequences(Optional> stopSequences); + + /** Clears the value of stopSequences field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearStopSequences() { + return stopSequences(Optional.empty()); + } + /** * Setter for responseLogprobs. * @@ -327,6 +474,16 @@ public Builder stopSequences(String... stopSequences) { @JsonProperty("responseLogprobs") public abstract Builder responseLogprobs(boolean responseLogprobs); + @ExcludeFromGeneratedCoverageReport + abstract Builder responseLogprobs(Optional responseLogprobs); + + /** Clears the value of responseLogprobs field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResponseLogprobs() { + return responseLogprobs(Optional.empty()); + } + /** * Setter for logprobs. * @@ -336,6 +493,16 @@ public Builder stopSequences(String... stopSequences) { @JsonProperty("logprobs") public abstract Builder logprobs(Integer logprobs); + @ExcludeFromGeneratedCoverageReport + abstract Builder logprobs(Optional logprobs); + + /** Clears the value of logprobs field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLogprobs() { + return logprobs(Optional.empty()); + } + /** * Setter for presencePenalty. * @@ -345,6 +512,16 @@ public Builder stopSequences(String... stopSequences) { @JsonProperty("presencePenalty") public abstract Builder presencePenalty(Float presencePenalty); + @ExcludeFromGeneratedCoverageReport + abstract Builder presencePenalty(Optional presencePenalty); + + /** Clears the value of presencePenalty field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPresencePenalty() { + return presencePenalty(Optional.empty()); + } + /** * Setter for frequencyPenalty. * @@ -354,6 +531,16 @@ public Builder stopSequences(String... stopSequences) { @JsonProperty("frequencyPenalty") public abstract Builder frequencyPenalty(Float frequencyPenalty); + @ExcludeFromGeneratedCoverageReport + abstract Builder frequencyPenalty(Optional frequencyPenalty); + + /** Clears the value of frequencyPenalty field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFrequencyPenalty() { + return frequencyPenalty(Optional.empty()); + } + /** * Setter for seed. * @@ -363,17 +550,37 @@ public Builder stopSequences(String... stopSequences) { @JsonProperty("seed") public abstract Builder seed(Integer seed); + @ExcludeFromGeneratedCoverageReport + abstract Builder seed(Optional seed); + + /** Clears the value of seed field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSeed() { + return seed(Optional.empty()); + } + /** * Setter for responseMimeType. * *

    responseMimeType: Output response mimetype of the generated candidate text. Supported * mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the * candidates. The model needs to be prompted to output the appropriate response type, otherwise - * the behavior is undefined. This is a preview feature. + * the behavior is undefined. */ @JsonProperty("responseMimeType") public abstract Builder responseMimeType(String responseMimeType); + @ExcludeFromGeneratedCoverageReport + abstract Builder responseMimeType(Optional responseMimeType); + + /** Clears the value of responseMimeType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResponseMimeType() { + return responseMimeType(Optional.empty()); + } + /** * Setter for responseSchema. * @@ -382,6 +589,9 @@ public Builder stopSequences(String... stopSequences) { * [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a * compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: * Schema for JSON response. + * + *

    If `response_schema` doesn't process your schema correctly, try using + * `response_json_schema` instead. */ @JsonProperty("responseSchema") public abstract Builder responseSchema(Schema responseSchema); @@ -394,11 +604,54 @@ public Builder stopSequences(String... stopSequences) { * [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a * compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: * Schema for JSON response. + * + *

    If `response_schema` doesn't process your schema correctly, try using + * `response_json_schema` instead. */ + @CanIgnoreReturnValue public Builder responseSchema(Schema.Builder responseSchemaBuilder) { return responseSchema(responseSchemaBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder responseSchema(Optional responseSchema); + + /** Clears the value of responseSchema field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResponseSchema() { + return responseSchema(Optional.empty()); + } + + /** + * Setter for responseJsonSchema. + * + *

    responseJsonSchema: Optional. Output schema of the generated response. This is an + * alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If + * set, `response_schema` must be omitted, but `response_mime_type` is required. While the full + * JSON Schema may be sent, not all features are supported. Specifically, only the following + * properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - + * `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - + * `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as + * `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard + * `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited + * degree and, as such, may only be used within non-required properties. (Nullable properties + * are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than + * those starting as a `$`, may be set. + */ + @JsonProperty("responseJsonSchema") + public abstract Builder responseJsonSchema(Object responseJsonSchema); + + @ExcludeFromGeneratedCoverageReport + abstract Builder responseJsonSchema(Optional responseJsonSchema); + + /** Clears the value of responseJsonSchema field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResponseJsonSchema() { + return responseJsonSchema(Optional.empty()); + } + /** * Setter for routingConfig. * @@ -412,10 +665,21 @@ public Builder responseSchema(Schema.Builder responseSchemaBuilder) { * *

    routingConfig: Configuration for model router requests. */ + @CanIgnoreReturnValue public Builder routingConfig(GenerationConfigRoutingConfig.Builder routingConfigBuilder) { return routingConfig(routingConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder routingConfig(Optional routingConfig); + + /** Clears the value of routingConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearRoutingConfig() { + return routingConfig(Optional.empty()); + } + /** * Setter for modelSelectionConfig. * @@ -429,10 +693,21 @@ public Builder routingConfig(GenerationConfigRoutingConfig.Builder routingConfig * *

    modelSelectionConfig: Configuration for model selection. */ + @CanIgnoreReturnValue public Builder modelSelectionConfig(ModelSelectionConfig.Builder modelSelectionConfigBuilder) { return modelSelectionConfig(modelSelectionConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder modelSelectionConfig(Optional modelSelectionConfig); + + /** Clears the value of modelSelectionConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModelSelectionConfig() { + return modelSelectionConfig(Optional.empty()); + } + /** * Setter for safetySettings. * @@ -446,6 +721,7 @@ public Builder modelSelectionConfig(ModelSelectionConfig.Builder modelSelectionC * *

    safetySettings: Safety settings in the request to block unsafe content in the response. */ + @CanIgnoreReturnValue public Builder safetySettings(SafetySetting... safetySettings) { return safetySettings(Arrays.asList(safetySettings)); } @@ -455,6 +731,7 @@ public Builder safetySettings(SafetySetting... safetySettings) { * *

    safetySettings: Safety settings in the request to block unsafe content in the response. */ + @CanIgnoreReturnValue public Builder safetySettings(SafetySetting.Builder... safetySettingsBuilders) { return safetySettings( Arrays.asList(safetySettingsBuilders).stream() @@ -462,6 +739,16 @@ public Builder safetySettings(SafetySetting.Builder... safetySettingsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder safetySettings(Optional> safetySettings); + + /** Clears the value of safetySettings field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSafetySettings() { + return safetySettings(Optional.empty()); + } + /** * Setter for tools. * @@ -477,6 +764,7 @@ public Builder safetySettings(SafetySetting.Builder... safetySettingsBuilders) { *

    tools: Code that enables the system to interact with external systems to perform an action * outside of the knowledge and scope of the model. */ + @CanIgnoreReturnValue public Builder tools(Tool... tools) { return tools(Arrays.asList(tools)); } @@ -487,6 +775,7 @@ public Builder tools(Tool... tools) { *

    tools: Code that enables the system to interact with external systems to perform an action * outside of the knowledge and scope of the model. */ + @CanIgnoreReturnValue public Builder tools(Tool.Builder... toolsBuilders) { return tools( Arrays.asList(toolsBuilders).stream() @@ -494,6 +783,16 @@ public Builder tools(Tool.Builder... toolsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder tools(Optional> tools); + + /** Clears the value of tools field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTools() { + return tools(Optional.empty()); + } + /** * Setter for toolConfig. * @@ -507,10 +806,21 @@ public Builder tools(Tool.Builder... toolsBuilders) { * *

    toolConfig: Associates model output to a specific function call. */ + @CanIgnoreReturnValue public Builder toolConfig(ToolConfig.Builder toolConfigBuilder) { return toolConfig(toolConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder toolConfig(Optional toolConfig); + + /** Clears the value of toolConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearToolConfig() { + return toolConfig(Optional.empty()); + } + /** * Setter for labels. * @@ -519,6 +829,16 @@ public Builder toolConfig(ToolConfig.Builder toolConfigBuilder) { @JsonProperty("labels") public abstract Builder labels(Map labels); + @ExcludeFromGeneratedCoverageReport + abstract Builder labels(Optional> labels); + + /** Clears the value of labels field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLabels() { + return labels(Optional.empty()); + } + /** * Setter for cachedContent. * @@ -527,6 +847,16 @@ public Builder toolConfig(ToolConfig.Builder toolConfigBuilder) { @JsonProperty("cachedContent") public abstract Builder cachedContent(String cachedContent); + @ExcludeFromGeneratedCoverageReport + abstract Builder cachedContent(Optional cachedContent); + + /** Clears the value of cachedContent field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCachedContent() { + return cachedContent(Optional.empty()); + } + /** * Setter for responseModalities. * @@ -542,10 +872,21 @@ public Builder toolConfig(ToolConfig.Builder toolConfigBuilder) { *

    responseModalities: The requested modalities of the response. Represents the set of * modalities that the model can return. */ + @CanIgnoreReturnValue public Builder responseModalities(String... responseModalities) { return responseModalities(Arrays.asList(responseModalities)); } + @ExcludeFromGeneratedCoverageReport + abstract Builder responseModalities(Optional> responseModalities); + + /** Clears the value of responseModalities field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResponseModalities() { + return responseModalities(Optional.empty()); + } + /** * Setter for mediaResolution. * @@ -554,21 +895,41 @@ public Builder responseModalities(String... responseModalities) { @JsonProperty("mediaResolution") public abstract Builder mediaResolution(MediaResolution mediaResolution); + @ExcludeFromGeneratedCoverageReport + abstract Builder mediaResolution(Optional mediaResolution); + + /** Clears the value of mediaResolution field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMediaResolution() { + return mediaResolution(Optional.empty()); + } + + /** + * Setter for mediaResolution given a known enum. + * + *

    mediaResolution: If specified, the media resolution specified will be used. + */ @CanIgnoreReturnValue public Builder mediaResolution(MediaResolution.Known knownType) { return mediaResolution(new MediaResolution(knownType)); } + /** + * Setter for mediaResolution given a string. + * + *

    mediaResolution: If specified, the media resolution specified will be used. + */ @CanIgnoreReturnValue public Builder mediaResolution(String mediaResolution) { return mediaResolution(new MediaResolution(mediaResolution)); } + /** * Setter for speechConfig. * *

    speechConfig: The speech generation configuration. */ - @JsonProperty("speechConfig") public abstract Builder speechConfig(SpeechConfig speechConfig); @@ -577,10 +938,21 @@ public Builder mediaResolution(String mediaResolution) { * *

    speechConfig: The speech generation configuration. */ + @CanIgnoreReturnValue public Builder speechConfig(SpeechConfig.Builder speechConfigBuilder) { return speechConfig(speechConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder speechConfig(Optional speechConfig); + + /** Clears the value of speechConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSpeechConfig() { + return speechConfig(Optional.empty()); + } + /** * Setter for audioTimestamp. * @@ -589,6 +961,16 @@ public Builder speechConfig(SpeechConfig.Builder speechConfigBuilder) { @JsonProperty("audioTimestamp") public abstract Builder audioTimestamp(boolean audioTimestamp); + @ExcludeFromGeneratedCoverageReport + abstract Builder audioTimestamp(Optional audioTimestamp); + + /** Clears the value of audioTimestamp field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAudioTimestamp() { + return audioTimestamp(Optional.empty()); + } + /** * Setter for automaticFunctionCalling. * @@ -603,11 +985,23 @@ public abstract Builder automaticFunctionCalling( * *

    automaticFunctionCalling: The configuration for automatic function calling. */ + @CanIgnoreReturnValue public Builder automaticFunctionCalling( AutomaticFunctionCallingConfig.Builder automaticFunctionCallingBuilder) { return automaticFunctionCalling(automaticFunctionCallingBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder automaticFunctionCalling( + Optional automaticFunctionCalling); + + /** Clears the value of automaticFunctionCalling field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAutomaticFunctionCalling() { + return automaticFunctionCalling(Optional.empty()); + } + /** * Setter for thinkingConfig. * @@ -621,14 +1015,141 @@ public Builder automaticFunctionCalling( * *

    thinkingConfig: The thinking features configuration. */ + @CanIgnoreReturnValue public Builder thinkingConfig(ThinkingConfig.Builder thinkingConfigBuilder) { return thinkingConfig(thinkingConfigBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder thinkingConfig(Optional thinkingConfig); + + /** Clears the value of thinkingConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearThinkingConfig() { + return thinkingConfig(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder imageConfig(ImageConfig.Builder imageConfigBuilder) { + return imageConfig(imageConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder imageConfig(Optional imageConfig); + + /** Clears the value of imageConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearImageConfig() { + return imageConfig(Optional.empty()); + } + + /** + * Setter for enableEnhancedCivicAnswers. + * + *

    enableEnhancedCivicAnswers: Enables enhanced civic answers. It may not be available for + * all models. This field is not supported in Gemini Enterprise Agent Platform. + */ + @JsonProperty("enableEnhancedCivicAnswers") + public abstract Builder enableEnhancedCivicAnswers(boolean enableEnhancedCivicAnswers); + + @ExcludeFromGeneratedCoverageReport + abstract Builder enableEnhancedCivicAnswers(Optional enableEnhancedCivicAnswers); + + /** Clears the value of enableEnhancedCivicAnswers field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEnableEnhancedCivicAnswers() { + return enableEnhancedCivicAnswers(Optional.empty()); + } + + /** + * Setter for modelArmorConfig. + * + *

    modelArmorConfig: Settings for prompt and response sanitization using the Model Armor + * service. If supplied, safety_settings must not be supplied. + */ + @JsonProperty("modelArmorConfig") + public abstract Builder modelArmorConfig(ModelArmorConfig modelArmorConfig); + + /** + * Setter for modelArmorConfig builder. + * + *

    modelArmorConfig: Settings for prompt and response sanitization using the Model Armor + * service. If supplied, safety_settings must not be supplied. + */ + @CanIgnoreReturnValue + public Builder modelArmorConfig(ModelArmorConfig.Builder modelArmorConfigBuilder) { + return modelArmorConfig(modelArmorConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder modelArmorConfig(Optional modelArmorConfig); + + /** Clears the value of modelArmorConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModelArmorConfig() { + return modelArmorConfig(Optional.empty()); + } + + /** + * Setter for serviceTier. + * + *

    serviceTier: The service tier to use for the request. For example, ServiceTier.FLEX. + */ + @JsonProperty("serviceTier") + public abstract Builder serviceTier(ServiceTier serviceTier); + + @ExcludeFromGeneratedCoverageReport + abstract Builder serviceTier(Optional serviceTier); + + /** Clears the value of serviceTier field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearServiceTier() { + return serviceTier(Optional.empty()); + } + + /** + * Setter for serviceTier given a known enum. + * + *

    serviceTier: The service tier to use for the request. For example, ServiceTier.FLEX. + */ + @CanIgnoreReturnValue + public Builder serviceTier(ServiceTier.Known knownType) { + return serviceTier(new ServiceTier(knownType)); + } + + /** + * Setter for serviceTier given a string. + * + *

    serviceTier: The service tier to use for the request. For example, ServiceTier.FLEX. + */ + @CanIgnoreReturnValue + public Builder serviceTier(String serviceTier) { + return serviceTier(new ServiceTier(serviceTier)); + } + 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..aabe08246ab 100644 --- a/src/main/java/com/google/genai/types/GenerateContentParameters.java +++ b/src/main/java/com/google/genai/types/GenerateContentParameters.java @@ -25,6 +25,7 @@ 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.Arrays; import java.util.List; @@ -51,6 +52,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(); } @@ -76,6 +78,16 @@ private static Builder create() { @JsonProperty("model") public abstract Builder model(String model); + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + /** * Setter for contents. * @@ -89,6 +101,7 @@ private static Builder create() { * *

    contents: Content of the request. */ + @CanIgnoreReturnValue public Builder contents(Content... contents) { return contents(Arrays.asList(contents)); } @@ -98,6 +111,7 @@ public Builder contents(Content... contents) { * *

    contents: Content of the request. */ + @CanIgnoreReturnValue public Builder contents(Content.Builder... contentsBuilders) { return contents( Arrays.asList(contentsBuilders).stream() @@ -105,6 +119,16 @@ public Builder contents(Content.Builder... contentsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder contents(Optional> contents); + + /** Clears the value of contents field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearContents() { + return contents(Optional.empty()); + } + /** * Setter for config. * @@ -118,14 +142,26 @@ public Builder contents(Content.Builder... contentsBuilders) { * *

    config: Configuration that contains optional model parameters. */ + @CanIgnoreReturnValue public Builder config(GenerateContentConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract GenerateContentParameters build(); } /** 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 4cf2b44b377..decb22d1b7b 100644 --- a/src/main/java/com/google/genai/types/GenerateContentResponse.java +++ b/src/main/java/com/google/genai/types/GenerateContentResponse.java @@ -27,6 +27,7 @@ import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; +import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.JsonSerializable; import java.time.Instant; import java.util.ArrayList; @@ -41,6 +42,10 @@ @AutoValue @JsonDeserialize(builder = GenerateContentResponse.Builder.class) public abstract class GenerateContentResponse extends JsonSerializable { + /** Used to retain the full HTTP response. */ + @JsonProperty("sdkHttpResponse") + public abstract Optional sdkHttpResponse(); + /** Response variations returned by the model. */ @JsonProperty("candidates") public abstract Optional> candidates(); @@ -49,10 +54,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(); @@ -68,11 +69,24 @@ 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(); + /** + * Output only. The current model status of this model. This field is not supported in Vertex AI. + */ + @JsonProperty("modelStatus") + public abstract Optional modelStatus(); + /** Instantiates a builder for GenerateContentResponse. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateContentResponse.Builder(); } @@ -89,6 +103,34 @@ private static Builder create() { return new AutoValue_GenerateContentResponse.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. + */ + @CanIgnoreReturnValue + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + /** * Setter for candidates. * @@ -102,6 +144,7 @@ private static Builder create() { * *

    candidates: Response variations returned by the model. */ + @CanIgnoreReturnValue public Builder candidates(Candidate... candidates) { return candidates(Arrays.asList(candidates)); } @@ -111,6 +154,7 @@ public Builder candidates(Candidate... candidates) { * *

    candidates: Response variations returned by the model. */ + @CanIgnoreReturnValue public Builder candidates(Candidate.Builder... candidatesBuilders) { return candidates( Arrays.asList(candidatesBuilders).stream() @@ -118,6 +162,16 @@ public Builder candidates(Candidate.Builder... candidatesBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder candidates(Optional> candidates); + + /** Clears the value of candidates field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCandidates() { + return candidates(Optional.empty()); + } + /** * Setter for createTime. * @@ -126,13 +180,15 @@ 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder createTime(Optional createTime); + + /** Clears the value of createTime field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCreateTime() { + return createTime(Optional.empty()); + } /** * Setter for automaticFunctionCallingHistory. @@ -148,6 +204,7 @@ public abstract Builder automaticFunctionCallingHistory( * *

    automaticFunctionCallingHistory: The history of automatic function calling. */ + @CanIgnoreReturnValue public Builder automaticFunctionCallingHistory(Content... automaticFunctionCallingHistory) { return automaticFunctionCallingHistory(Arrays.asList(automaticFunctionCallingHistory)); } @@ -157,6 +214,7 @@ public Builder automaticFunctionCallingHistory(Content... automaticFunctionCalli * *

    automaticFunctionCallingHistory: The history of automatic function calling. */ + @CanIgnoreReturnValue public Builder automaticFunctionCallingHistory( Content.Builder... automaticFunctionCallingHistoryBuilders) { return automaticFunctionCallingHistory( @@ -165,6 +223,17 @@ public Builder automaticFunctionCallingHistory( .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder automaticFunctionCallingHistory( + Optional> automaticFunctionCallingHistory); + + /** Clears the value of automaticFunctionCallingHistory field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAutomaticFunctionCallingHistory() { + return automaticFunctionCallingHistory(Optional.empty()); + } + /** * Setter for modelVersion. * @@ -173,6 +242,16 @@ public Builder automaticFunctionCallingHistory( @JsonProperty("modelVersion") public abstract Builder modelVersion(String modelVersion); + @ExcludeFromGeneratedCoverageReport + abstract Builder modelVersion(Optional modelVersion); + + /** Clears the value of modelVersion field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModelVersion() { + return modelVersion(Optional.empty()); + } + /** * Setter for promptFeedback. * @@ -190,11 +269,41 @@ public Builder automaticFunctionCallingHistory( * Note: Sent only in the first stream chunk. Only happens when no candidates were generated due * to content violations. */ + @CanIgnoreReturnValue public Builder promptFeedback( GenerateContentResponsePromptFeedback.Builder promptFeedbackBuilder) { return promptFeedback(promptFeedbackBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder promptFeedback(Optional promptFeedback); + + /** Clears the value of promptFeedback field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPromptFeedback() { + return promptFeedback(Optional.empty()); + } + + /** + * 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder responseId(Optional responseId); + + /** Clears the value of responseId field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResponseId() { + return responseId(Optional.empty()); + } + /** * Setter for usageMetadata. * @@ -208,15 +317,57 @@ public Builder promptFeedback( * *

    usageMetadata: Usage metadata about the response(s). */ + @CanIgnoreReturnValue public Builder usageMetadata( GenerateContentResponseUsageMetadata.Builder usageMetadataBuilder) { return usageMetadata(usageMetadataBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder usageMetadata(Optional usageMetadata); + + /** Clears the value of usageMetadata field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearUsageMetadata() { + return usageMetadata(Optional.empty()); + } + + /** + * Setter for modelStatus. + * + *

    modelStatus: Output only. The current model status of this model. This field is not + * supported in Vertex AI. + */ + @JsonProperty("modelStatus") + public abstract Builder modelStatus(ModelStatus modelStatus); + + /** + * Setter for modelStatus builder. + * + *

    modelStatus: Output only. The current model status of this model. This field is not + * supported in Vertex AI. + */ + @CanIgnoreReturnValue + public Builder modelStatus(ModelStatus.Builder modelStatusBuilder) { + return modelStatus(modelStatusBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder modelStatus(Optional modelStatus); + + /** Clears the value of modelStatus field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModelStatus() { + return modelStatus(Optional.empty()); + } + public abstract GenerateContentResponse build(); } /** 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 5bb67c1aba0..b42304de4bf 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,33 +76,65 @@ 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder blockReason(Optional blockReason); + + /** Clears the value of blockReason field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBlockReason() { + return blockReason(Optional.empty()); + } + + /** + * Setter for blockReason given a known enum. + * + *

    blockReason: Output only. The reason why the prompt was blocked. + */ @CanIgnoreReturnValue public Builder blockReason(BlockedReason.Known knownType) { return blockReason(new BlockedReason(knownType)); } + /** + * Setter for blockReason given a string. + * + *

    blockReason: Output only. The reason why the prompt was blocked. + */ @CanIgnoreReturnValue public Builder blockReason(String blockReason) { return blockReason(new BlockedReason(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); + @ExcludeFromGeneratedCoverageReport + abstract Builder blockReasonMessage(Optional blockReasonMessage); + + /** Clears the value of blockReasonMessage field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearBlockReasonMessage() { + return blockReasonMessage(Optional.empty()); + } + /** * 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); @@ -103,8 +142,10 @@ 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. */ + @CanIgnoreReturnValue public Builder safetyRatings(SafetyRating... safetyRatings) { return safetyRatings(Arrays.asList(safetyRatings)); } @@ -112,8 +153,10 @@ 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. */ + @CanIgnoreReturnValue public Builder safetyRatings(SafetyRating.Builder... safetyRatingsBuilders) { return safetyRatings( Arrays.asList(safetyRatingsBuilders).stream() @@ -121,10 +164,21 @@ public Builder safetyRatings(SafetyRating.Builder... safetyRatingsBuilders) { .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder safetyRatings(Optional> safetyRatings); + + /** Clears the value of safetyRatings field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSafetyRatings() { + return safetyRatings(Optional.empty()); + } + public abstract GenerateContentResponsePromptFeedback build(); } /** 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 5bb3605ac25..f01a6e5b1df 100644 --- a/src/main/java/com/google/genai/types/GenerateContentResponseUsageMetadata.java +++ b/src/main/java/com/google/genai/types/GenerateContentResponseUsageMetadata.java @@ -30,61 +30,81 @@ import java.util.List; import java.util.Optional; -/** Usage metadata about response(s). */ +/** + * Usage metadata about the content generation request and response. This message provides a + * detailed breakdown of token usage and other relevant metrics. This data type is not supported in + * Gemini API. + */ @AutoValue @JsonDeserialize(builder = GenerateContentResponseUsageMetadata.Builder.class) public abstract class GenerateContentResponseUsageMetadata extends JsonSerializable { - /** Output only. List of modalities of the cached content in the request input. */ + /** + * Output only. A detailed breakdown of the token count for each modality in the cached content. + */ @JsonProperty("cacheTokensDetails") public abstract Optional> cacheTokensDetails(); - /** Output only. Number of tokens in the cached part in the input (the cached content). */ + /** Output only. The number of tokens in the cached content that was used for this request. */ @JsonProperty("cachedContentTokenCount") public abstract Optional cachedContentTokenCount(); - /** Number of tokens in the response(s). */ + /** The total number of tokens in the generated candidates. */ @JsonProperty("candidatesTokenCount") public abstract Optional candidatesTokenCount(); - /** Output only. List of modalities that were returned in the response. */ + /** + * Output only. A detailed breakdown of the token count for each modality in the generated + * candidates. + */ @JsonProperty("candidatesTokensDetails") public abstract Optional> candidatesTokensDetails(); /** - * Number of tokens in the request. When `cached_content` is set, this is still the total - * effective prompt size meaning this includes the number of tokens in the cached content. + * The total number of tokens in the prompt. This includes any text, images, or other media + * provided in the request. When `cached_content` is set, this also includes the number of tokens + * in the cached content. */ @JsonProperty("promptTokenCount") public abstract Optional promptTokenCount(); - /** Output only. List of modalities that were processed in the request input. */ + /** Output only. A detailed breakdown of the token count for each modality in the prompt. */ @JsonProperty("promptTokensDetails") public abstract Optional> promptTokensDetails(); - /** Output only. Number of tokens present in thoughts output. */ + /** + * Output only. The number of tokens that were part of the model's generated "thoughts" output, if + * applicable. + */ @JsonProperty("thoughtsTokenCount") public abstract Optional thoughtsTokenCount(); - /** Output only. Number of tokens present in tool-use prompt(s). */ + /** + * Output only. The number of tokens in the results from tool executions, which are provided back + * to the model as input, if applicable. + */ @JsonProperty("toolUsePromptTokenCount") public abstract Optional toolUsePromptTokenCount(); - /** Output only. List of modalities that were processed for tool-use request inputs. */ + /** + * Output only. A detailed breakdown by modality of the token counts from the results of tool + * executions, which are provided back to the model as input. + */ @JsonProperty("toolUsePromptTokensDetails") public abstract Optional> toolUsePromptTokensDetails(); - /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + /** + * The total number of tokens for the entire request. This is the sum of `prompt_token_count`, + * `candidates_token_count`, `tool_use_prompt_token_count`, and `thoughts_token_count`. + */ @JsonProperty("totalTokenCount") public abstract Optional totalTokenCount(); - /** - * Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned - * Throughput quota. - */ + /** Output only. The traffic type for this request. */ @JsonProperty("trafficType") public abstract Optional trafficType(); /** Instantiates a builder for GenerateContentResponseUsageMetadata. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateContentResponseUsageMetadata.Builder(); } @@ -107,8 +127,8 @@ private static Builder create() { /** * Setter for cacheTokensDetails. * - *

    cacheTokensDetails: Output only. List of modalities of the cached content in the request - * input. + *

    cacheTokensDetails: Output only. A detailed breakdown of the token count for each modality + * in the cached content. */ @JsonProperty("cacheTokensDetails") public abstract Builder cacheTokensDetails(List cacheTokensDetails); @@ -116,9 +136,10 @@ private static Builder create() { /** * Setter for cacheTokensDetails. * - *

    cacheTokensDetails: Output only. List of modalities of the cached content in the request - * input. + *

    cacheTokensDetails: Output only. A detailed breakdown of the token count for each modality + * in the cached content. */ + @CanIgnoreReturnValue public Builder cacheTokensDetails(ModalityTokenCount... cacheTokensDetails) { return cacheTokensDetails(Arrays.asList(cacheTokensDetails)); } @@ -126,9 +147,10 @@ public Builder cacheTokensDetails(ModalityTokenCount... cacheTokensDetails) { /** * Setter for cacheTokensDetails builder. * - *

    cacheTokensDetails: Output only. List of modalities of the cached content in the request - * input. + *

    cacheTokensDetails: Output only. A detailed breakdown of the token count for each modality + * in the cached content. */ + @CanIgnoreReturnValue public Builder cacheTokensDetails(ModalityTokenCount.Builder... cacheTokensDetailsBuilders) { return cacheTokensDetails( Arrays.asList(cacheTokensDetailsBuilders).stream() @@ -136,28 +158,58 @@ public Builder cacheTokensDetails(ModalityTokenCount.Builder... cacheTokensDetai .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder cacheTokensDetails(Optional> cacheTokensDetails); + + /** Clears the value of cacheTokensDetails field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCacheTokensDetails() { + return cacheTokensDetails(Optional.empty()); + } + /** * Setter for cachedContentTokenCount. * - *

    cachedContentTokenCount: Output only. Number of tokens in the cached part in the input - * (the cached content). + *

    cachedContentTokenCount: Output only. The number of tokens in the cached content that was + * used for this request. */ @JsonProperty("cachedContentTokenCount") public abstract Builder cachedContentTokenCount(Integer cachedContentTokenCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder cachedContentTokenCount(Optional cachedContentTokenCount); + + /** Clears the value of cachedContentTokenCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCachedContentTokenCount() { + return cachedContentTokenCount(Optional.empty()); + } + /** * Setter for candidatesTokenCount. * - *

    candidatesTokenCount: Number of tokens in the response(s). + *

    candidatesTokenCount: The total number of tokens in the generated candidates. */ @JsonProperty("candidatesTokenCount") public abstract Builder candidatesTokenCount(Integer candidatesTokenCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder candidatesTokenCount(Optional candidatesTokenCount); + + /** Clears the value of candidatesTokenCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCandidatesTokenCount() { + return candidatesTokenCount(Optional.empty()); + } + /** * Setter for candidatesTokensDetails. * - *

    candidatesTokensDetails: Output only. List of modalities that were returned in the - * response. + *

    candidatesTokensDetails: Output only. A detailed breakdown of the token count for each + * modality in the generated candidates. */ @JsonProperty("candidatesTokensDetails") public abstract Builder candidatesTokensDetails( @@ -166,9 +218,10 @@ public abstract Builder candidatesTokensDetails( /** * Setter for candidatesTokensDetails. * - *

    candidatesTokensDetails: Output only. List of modalities that were returned in the - * response. + *

    candidatesTokensDetails: Output only. A detailed breakdown of the token count for each + * modality in the generated candidates. */ + @CanIgnoreReturnValue public Builder candidatesTokensDetails(ModalityTokenCount... candidatesTokensDetails) { return candidatesTokensDetails(Arrays.asList(candidatesTokensDetails)); } @@ -176,9 +229,10 @@ public Builder candidatesTokensDetails(ModalityTokenCount... candidatesTokensDet /** * Setter for candidatesTokensDetails builder. * - *

    candidatesTokensDetails: Output only. List of modalities that were returned in the - * response. + *

    candidatesTokensDetails: Output only. A detailed breakdown of the token count for each + * modality in the generated candidates. */ + @CanIgnoreReturnValue public Builder candidatesTokensDetails( ModalityTokenCount.Builder... candidatesTokensDetailsBuilders) { return candidatesTokensDetails( @@ -187,21 +241,42 @@ public Builder candidatesTokensDetails( .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder candidatesTokensDetails( + Optional> candidatesTokensDetails); + + /** Clears the value of candidatesTokensDetails field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCandidatesTokensDetails() { + return candidatesTokensDetails(Optional.empty()); + } + /** * Setter for promptTokenCount. * - *

    promptTokenCount: Number of tokens in the request. When `cached_content` is set, this is - * still the total effective prompt size meaning this includes the number of tokens in the - * cached content. + *

    promptTokenCount: The total number of tokens in the prompt. This includes any text, + * images, or other media provided in the request. When `cached_content` is set, this also + * includes the number of tokens in the cached content. */ @JsonProperty("promptTokenCount") public abstract Builder promptTokenCount(Integer promptTokenCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder promptTokenCount(Optional promptTokenCount); + + /** Clears the value of promptTokenCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPromptTokenCount() { + return promptTokenCount(Optional.empty()); + } + /** * Setter for promptTokensDetails. * - *

    promptTokensDetails: Output only. List of modalities that were processed in the request - * input. + *

    promptTokensDetails: Output only. A detailed breakdown of the token count for each + * modality in the prompt. */ @JsonProperty("promptTokensDetails") public abstract Builder promptTokensDetails(List promptTokensDetails); @@ -209,9 +284,10 @@ public Builder candidatesTokensDetails( /** * Setter for promptTokensDetails. * - *

    promptTokensDetails: Output only. List of modalities that were processed in the request - * input. + *

    promptTokensDetails: Output only. A detailed breakdown of the token count for each + * modality in the prompt. */ + @CanIgnoreReturnValue public Builder promptTokensDetails(ModalityTokenCount... promptTokensDetails) { return promptTokensDetails(Arrays.asList(promptTokensDetails)); } @@ -219,9 +295,10 @@ public Builder promptTokensDetails(ModalityTokenCount... promptTokensDetails) { /** * Setter for promptTokensDetails builder. * - *

    promptTokensDetails: Output only. List of modalities that were processed in the request - * input. + *

    promptTokensDetails: Output only. A detailed breakdown of the token count for each + * modality in the prompt. */ + @CanIgnoreReturnValue public Builder promptTokensDetails(ModalityTokenCount.Builder... promptTokensDetailsBuilders) { return promptTokensDetails( Arrays.asList(promptTokensDetailsBuilders).stream() @@ -229,27 +306,59 @@ public Builder promptTokensDetails(ModalityTokenCount.Builder... promptTokensDet .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder promptTokensDetails(Optional> promptTokensDetails); + + /** Clears the value of promptTokensDetails field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPromptTokensDetails() { + return promptTokensDetails(Optional.empty()); + } + /** * Setter for thoughtsTokenCount. * - *

    thoughtsTokenCount: Output only. Number of tokens present in thoughts output. + *

    thoughtsTokenCount: Output only. The number of tokens that were part of the model's + * generated "thoughts" output, if applicable. */ @JsonProperty("thoughtsTokenCount") public abstract Builder thoughtsTokenCount(Integer thoughtsTokenCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder thoughtsTokenCount(Optional thoughtsTokenCount); + + /** Clears the value of thoughtsTokenCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearThoughtsTokenCount() { + return thoughtsTokenCount(Optional.empty()); + } + /** * Setter for toolUsePromptTokenCount. * - *

    toolUsePromptTokenCount: Output only. Number of tokens present in tool-use prompt(s). + *

    toolUsePromptTokenCount: Output only. The number of tokens in the results from tool + * executions, which are provided back to the model as input, if applicable. */ @JsonProperty("toolUsePromptTokenCount") public abstract Builder toolUsePromptTokenCount(Integer toolUsePromptTokenCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder toolUsePromptTokenCount(Optional toolUsePromptTokenCount); + + /** Clears the value of toolUsePromptTokenCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearToolUsePromptTokenCount() { + return toolUsePromptTokenCount(Optional.empty()); + } + /** * Setter for toolUsePromptTokensDetails. * - *

    toolUsePromptTokensDetails: Output only. List of modalities that were processed for - * tool-use request inputs. + *

    toolUsePromptTokensDetails: Output only. A detailed breakdown by modality of the token + * counts from the results of tool executions, which are provided back to the model as input. */ @JsonProperty("toolUsePromptTokensDetails") public abstract Builder toolUsePromptTokensDetails( @@ -258,9 +367,10 @@ public abstract Builder toolUsePromptTokensDetails( /** * Setter for toolUsePromptTokensDetails. * - *

    toolUsePromptTokensDetails: Output only. List of modalities that were processed for - * tool-use request inputs. + *

    toolUsePromptTokensDetails: Output only. A detailed breakdown by modality of the token + * counts from the results of tool executions, which are provided back to the model as input. */ + @CanIgnoreReturnValue public Builder toolUsePromptTokensDetails(ModalityTokenCount... toolUsePromptTokensDetails) { return toolUsePromptTokensDetails(Arrays.asList(toolUsePromptTokensDetails)); } @@ -268,9 +378,10 @@ public Builder toolUsePromptTokensDetails(ModalityTokenCount... toolUsePromptTok /** * Setter for toolUsePromptTokensDetails builder. * - *

    toolUsePromptTokensDetails: Output only. List of modalities that were processed for - * tool-use request inputs. + *

    toolUsePromptTokensDetails: Output only. A detailed breakdown by modality of the token + * counts from the results of tool executions, which are provided back to the model as input. */ + @CanIgnoreReturnValue public Builder toolUsePromptTokensDetails( ModalityTokenCount.Builder... toolUsePromptTokensDetailsBuilders) { return toolUsePromptTokensDetails( @@ -279,29 +390,70 @@ public Builder toolUsePromptTokensDetails( .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder toolUsePromptTokensDetails( + Optional> toolUsePromptTokensDetails); + + /** Clears the value of toolUsePromptTokensDetails field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearToolUsePromptTokensDetails() { + return toolUsePromptTokensDetails(Optional.empty()); + } + /** * Setter for totalTokenCount. * - *

    totalTokenCount: Total token count for prompt, response candidates, and tool-use prompts - * (if present). + *

    totalTokenCount: The total number of tokens for the entire request. This is the sum of + * `prompt_token_count`, `candidates_token_count`, `tool_use_prompt_token_count`, and + * `thoughts_token_count`. */ @JsonProperty("totalTokenCount") public abstract Builder totalTokenCount(Integer totalTokenCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder totalTokenCount(Optional totalTokenCount); + + /** Clears the value of totalTokenCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTotalTokenCount() { + return totalTokenCount(Optional.empty()); + } + /** * Setter for trafficType. * - *

    trafficType: Output only. Traffic type. This shows whether a request consumes - * Pay-As-You-Go or Provisioned Throughput quota. + *

    trafficType: Output only. The traffic type for this request. */ @JsonProperty("trafficType") public abstract Builder trafficType(TrafficType trafficType); + @ExcludeFromGeneratedCoverageReport + abstract Builder trafficType(Optional trafficType); + + /** Clears the value of trafficType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearTrafficType() { + return trafficType(Optional.empty()); + } + + /** + * Setter for trafficType given a known enum. + * + *

    trafficType: Output only. The traffic type for this request. + */ @CanIgnoreReturnValue public Builder trafficType(TrafficType.Known knownType) { return trafficType(new TrafficType(knownType)); } + /** + * Setter for trafficType given a string. + * + *

    trafficType: Output only. The traffic type for this request. + */ @CanIgnoreReturnValue public Builder trafficType(String trafficType) { return trafficType(new TrafficType(trafficType)); @@ -311,6 +463,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 f51d2a76400..ead88f4d43b 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. */ @@ -46,7 +47,10 @@ public abstract class GenerateImagesConfig extends JsonSerializable { @JsonProperty("numberOfImages") public abstract Optional numberOfImages(); - /** Aspect ratio of the generated images. */ + /** + * Aspect ratio of the generated images. Supported values are "1:1", "3:4", "4:3", "9:16", and + * "16:9". + */ @JsonProperty("aspectRatio") public abstract Optional aspectRatio(); @@ -101,11 +105,23 @@ 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). + */ + @JsonProperty("imageSize") + public abstract Optional imageSize(); + /** Whether to use the prompt rewriting logic. */ @JsonProperty("enhancePrompt") public abstract Optional enhancePrompt(); /** Instantiates a builder for GenerateImagesConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateImagesConfig.Builder(); } @@ -135,10 +151,21 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + /** * Setter for outputGcsUri. * @@ -147,6 +174,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("outputGcsUri") public abstract Builder outputGcsUri(String outputGcsUri); + @ExcludeFromGeneratedCoverageReport + abstract Builder outputGcsUri(Optional outputGcsUri); + + /** Clears the value of outputGcsUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputGcsUri() { + return outputGcsUri(Optional.empty()); + } + /** * Setter for negativePrompt. * @@ -155,6 +192,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("negativePrompt") public abstract Builder negativePrompt(String negativePrompt); + @ExcludeFromGeneratedCoverageReport + abstract Builder negativePrompt(Optional negativePrompt); + + /** Clears the value of negativePrompt field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearNegativePrompt() { + return negativePrompt(Optional.empty()); + } + /** * Setter for numberOfImages. * @@ -163,14 +210,35 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("numberOfImages") public abstract Builder numberOfImages(Integer numberOfImages); + @ExcludeFromGeneratedCoverageReport + abstract Builder numberOfImages(Optional numberOfImages); + + /** Clears the value of numberOfImages field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearNumberOfImages() { + return numberOfImages(Optional.empty()); + } + /** * Setter for aspectRatio. * - *

    aspectRatio: Aspect ratio of the generated images. + *

    aspectRatio: Aspect ratio of the generated images. Supported values are "1:1", "3:4", + * "4:3", "9:16", and "16:9". */ @JsonProperty("aspectRatio") public abstract Builder aspectRatio(String aspectRatio); + @ExcludeFromGeneratedCoverageReport + abstract Builder aspectRatio(Optional aspectRatio); + + /** Clears the value of aspectRatio field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAspectRatio() { + return aspectRatio(Optional.empty()); + } + /** * Setter for guidanceScale. * @@ -180,6 +248,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("guidanceScale") public abstract Builder guidanceScale(Float guidanceScale); + @ExcludeFromGeneratedCoverageReport + abstract Builder guidanceScale(Optional guidanceScale); + + /** Clears the value of guidanceScale field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGuidanceScale() { + return guidanceScale(Optional.empty()); + } + /** * Setter for seed. * @@ -189,6 +267,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("seed") public abstract Builder seed(Integer seed); + @ExcludeFromGeneratedCoverageReport + abstract Builder seed(Optional seed); + + /** Clears the value of seed field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSeed() { + return seed(Optional.empty()); + } + /** * Setter for safetyFilterLevel. * @@ -197,43 +285,93 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("safetyFilterLevel") public abstract Builder safetyFilterLevel(SafetyFilterLevel safetyFilterLevel); + @ExcludeFromGeneratedCoverageReport + abstract Builder safetyFilterLevel(Optional safetyFilterLevel); + + /** Clears the value of safetyFilterLevel field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSafetyFilterLevel() { + return safetyFilterLevel(Optional.empty()); + } + + /** + * 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder personGeneration(Optional personGeneration); + + /** Clears the value of personGeneration field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPersonGeneration() { + return personGeneration(Optional.empty()); + } + + /** + * 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 includeSafetyAttributes. * *

    includeSafetyAttributes: Whether to report the safety scores of each generated image and * the positive prompt in the response. */ - @JsonProperty("includeSafetyAttributes") public abstract Builder includeSafetyAttributes(boolean includeSafetyAttributes); + @ExcludeFromGeneratedCoverageReport + abstract Builder includeSafetyAttributes(Optional includeSafetyAttributes); + + /** Clears the value of includeSafetyAttributes field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearIncludeSafetyAttributes() { + return includeSafetyAttributes(Optional.empty()); + } + /** * Setter for includeRaiReason. * @@ -243,6 +381,16 @@ public Builder personGeneration(String personGeneration) { @JsonProperty("includeRaiReason") public abstract Builder includeRaiReason(boolean includeRaiReason); + @ExcludeFromGeneratedCoverageReport + abstract Builder includeRaiReason(Optional includeRaiReason); + + /** Clears the value of includeRaiReason field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearIncludeRaiReason() { + return includeRaiReason(Optional.empty()); + } + /** * Setter for language. * @@ -251,24 +399,54 @@ public Builder personGeneration(String personGeneration) { @JsonProperty("language") public abstract Builder language(ImagePromptLanguage language); + @ExcludeFromGeneratedCoverageReport + abstract Builder language(Optional language); + + /** Clears the value of language field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLanguage() { + return language(Optional.empty()); + } + + /** + * Setter for language given a known enum. + * + *

    language: Language of the text in the prompt. + */ @CanIgnoreReturnValue public Builder language(ImagePromptLanguage.Known knownType) { return language(new ImagePromptLanguage(knownType)); } + /** + * Setter for language given a string. + * + *

    language: Language of the text in the prompt. + */ @CanIgnoreReturnValue public Builder language(String language) { return language(new ImagePromptLanguage(language)); } + /** * Setter for outputMimeType. * *

    outputMimeType: MIME type of the generated image. */ - @JsonProperty("outputMimeType") public abstract Builder outputMimeType(String outputMimeType); + @ExcludeFromGeneratedCoverageReport + abstract Builder outputMimeType(Optional outputMimeType); + + /** Clears the value of outputMimeType field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputMimeType() { + return outputMimeType(Optional.empty()); + } + /** * Setter for outputCompressionQuality. * @@ -278,6 +456,16 @@ public Builder language(String language) { @JsonProperty("outputCompressionQuality") public abstract Builder outputCompressionQuality(Integer outputCompressionQuality); + @ExcludeFromGeneratedCoverageReport + abstract Builder outputCompressionQuality(Optional outputCompressionQuality); + + /** Clears the value of outputCompressionQuality field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputCompressionQuality() { + return outputCompressionQuality(Optional.empty()); + } + /** * Setter for addWatermark. * @@ -286,6 +474,53 @@ public Builder language(String language) { @JsonProperty("addWatermark") public abstract Builder addWatermark(boolean addWatermark); + @ExcludeFromGeneratedCoverageReport + abstract Builder addWatermark(Optional addWatermark); + + /** Clears the value of addWatermark field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAddWatermark() { + return addWatermark(Optional.empty()); + } + + /** + * Setter for labels. + * + *

    labels: User specified labels to track billing usage. + */ + @JsonProperty("labels") + public abstract Builder labels(Map labels); + + @ExcludeFromGeneratedCoverageReport + abstract Builder labels(Optional> labels); + + /** Clears the value of labels field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLabels() { + return labels(Optional.empty()); + } + + /** + * Setter for imageSize. + * + *

    imageSize: The size of the largest dimension of the generated image. Supported sizes are + * 1K and 2K (not supported for Imagen 3 models). + */ + @JsonProperty("imageSize") + public abstract Builder imageSize(String imageSize); + + @ExcludeFromGeneratedCoverageReport + abstract Builder imageSize(Optional imageSize); + + /** Clears the value of imageSize field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearImageSize() { + return imageSize(Optional.empty()); + } + /** * Setter for enhancePrompt. * @@ -294,10 +529,21 @@ public Builder language(String language) { @JsonProperty("enhancePrompt") public abstract Builder enhancePrompt(boolean enhancePrompt); + @ExcludeFromGeneratedCoverageReport + abstract Builder enhancePrompt(Optional enhancePrompt); + + /** Clears the value of enhancePrompt field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEnhancePrompt() { + return enhancePrompt(Optional.empty()); + } + public abstract GenerateImagesConfig build(); } /** 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..0f8515d131f 100644 --- a/src/main/java/com/google/genai/types/GenerateImagesParameters.java +++ b/src/main/java/com/google/genai/types/GenerateImagesParameters.java @@ -23,6 +23,7 @@ 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; @@ -47,6 +48,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(); } @@ -72,6 +74,16 @@ private static Builder create() { @JsonProperty("model") public abstract Builder model(String model); + @ExcludeFromGeneratedCoverageReport + abstract Builder model(Optional model); + + /** Clears the value of model field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearModel() { + return model(Optional.empty()); + } + /** * Setter for prompt. * @@ -80,6 +92,16 @@ private static Builder create() { @JsonProperty("prompt") public abstract Builder prompt(String prompt); + @ExcludeFromGeneratedCoverageReport + abstract Builder prompt(Optional prompt); + + /** Clears the value of prompt field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPrompt() { + return prompt(Optional.empty()); + } + /** * Setter for config. * @@ -93,14 +115,26 @@ private static Builder create() { * *

    config: Configuration for generating images. */ + @CanIgnoreReturnValue public Builder config(GenerateImagesConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract GenerateImagesParameters build(); } /** 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..947a0f53dc3 100644 --- a/src/main/java/com/google/genai/types/GenerateImagesResponse.java +++ b/src/main/java/com/google/genai/types/GenerateImagesResponse.java @@ -24,15 +24,23 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; +import com.google.common.collect.ImmutableList; +import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.genai.JsonSerializable; import java.util.Arrays; import java.util.List; import java.util.Optional; +import java.util.stream.Stream; +import org.jspecify.annotations.Nullable; /** The output images response. */ @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 +53,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 +70,34 @@ 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. + */ + @CanIgnoreReturnValue + public Builder sdkHttpResponse(HttpResponse.Builder sdkHttpResponseBuilder) { + return sdkHttpResponse(sdkHttpResponseBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder sdkHttpResponse(Optional sdkHttpResponse); + + /** Clears the value of sdkHttpResponse field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSdkHttpResponse() { + return sdkHttpResponse(Optional.empty()); + } + /** * Setter for generatedImages. * @@ -74,6 +111,7 @@ private static Builder create() { * *

    generatedImages: List of generated images. */ + @CanIgnoreReturnValue public Builder generatedImages(GeneratedImage... generatedImages) { return generatedImages(Arrays.asList(generatedImages)); } @@ -83,6 +121,7 @@ public Builder generatedImages(GeneratedImage... generatedImages) { * *

    generatedImages: List of generated images. */ + @CanIgnoreReturnValue public Builder generatedImages(GeneratedImage.Builder... generatedImagesBuilders) { return generatedImages( Arrays.asList(generatedImagesBuilders).stream() @@ -90,6 +129,16 @@ public Builder generatedImages(GeneratedImage.Builder... generatedImagesBuilders .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder generatedImages(Optional> generatedImages); + + /** Clears the value of generatedImages field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGeneratedImages() { + return generatedImages(Optional.empty()); + } + /** * Setter for positivePromptSafetyAttributes. * @@ -106,16 +155,50 @@ public abstract Builder positivePromptSafetyAttributes( *

    positivePromptSafetyAttributes: Safety attributes of the positive prompt. Only populated * if ``include_safety_attributes`` is set to True. */ + @CanIgnoreReturnValue public Builder positivePromptSafetyAttributes( SafetyAttributes.Builder positivePromptSafetyAttributesBuilder) { return positivePromptSafetyAttributes(positivePromptSafetyAttributesBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder positivePromptSafetyAttributes( + Optional positivePromptSafetyAttributes); + + /** Clears the value of positivePromptSafetyAttributes field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPositivePromptSafetyAttributes() { + return positivePromptSafetyAttributes(Optional.empty()); + } + public abstract GenerateImagesResponse build(); } /** Deserializes a JSON string to a GenerateImagesResponse object. */ + @ExcludeFromGeneratedCoverageReport public static GenerateImagesResponse fromJson(String jsonString) { return JsonSerializable.fromJsonString(jsonString, GenerateImagesResponse.class); } + + /** + * Returns the list of images from the response. + * + *

    Returns null if there are no generated images in the response. + */ + public @Nullable ImmutableList images() { + + Optional> generatedImages = generatedImages(); + if (!generatedImages.isPresent() || generatedImages.get().isEmpty()) { + return null; + } + + return ImmutableList.copyOf( + generatedImages.get().stream() + .map(GeneratedImage::image) + .flatMap( + optionalImage -> + optionalImage.isPresent() ? Stream.of(optionalImage.get()) : Stream.empty()) + .collect(toImmutableList())); + } } diff --git a/src/main/java/com/google/genai/types/GenerateVideosConfig.java b/src/main/java/com/google/genai/types/GenerateVideosConfig.java index 32605aebcec..b40b56e3c62 100644 --- a/src/main/java/com/google/genai/types/GenerateVideosConfig.java +++ b/src/main/java/com/google/genai/types/GenerateVideosConfig.java @@ -18,11 +18,17 @@ 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; /** Configuration for generating videos. */ @@ -63,7 +69,7 @@ public abstract class GenerateVideosConfig extends JsonSerializable { @JsonProperty("aspectRatio") public abstract Optional aspectRatio(); - /** The resolution for the generated video. 1280x720, 1920x1080 are supported. */ + /** The resolution for the generated video. 720p and 1080p are supported. */ @JsonProperty("resolution") public abstract Optional resolution(); @@ -78,10 +84,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(); @@ -93,7 +96,47 @@ public abstract class GenerateVideosConfig extends JsonSerializable { @JsonProperty("generateAudio") public abstract Optional generateAudio(); + /** + * Image to use as the last frame of generated videos. Only supported for image to video use + * cases. + */ + @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(); + + /** User specified labels to track billing usage. */ + @JsonProperty("labels") + public abstract Optional> labels(); + + /** + * Webhook configuration for receiving notifications when the video generation operation + * completes. + */ + @JsonProperty("webhookConfig") + public abstract Optional webhookConfig(); + + /** Resize mode of the image input for video generation. */ + @JsonProperty("resizeMode") + public abstract Optional resizeMode(); + /** Instantiates a builder for GenerateVideosConfig. */ + @ExcludeFromGeneratedCoverageReport public static Builder builder() { return new AutoValue_GenerateVideosConfig.Builder(); } @@ -123,10 +166,21 @@ private static Builder create() { * *

    httpOptions: Used to override HTTP request options. */ + @CanIgnoreReturnValue public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { return httpOptions(httpOptionsBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder httpOptions(Optional httpOptions); + + /** Clears the value of httpOptions field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearHttpOptions() { + return httpOptions(Optional.empty()); + } + /** * Setter for numberOfVideos. * @@ -135,6 +189,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("numberOfVideos") public abstract Builder numberOfVideos(Integer numberOfVideos); + @ExcludeFromGeneratedCoverageReport + abstract Builder numberOfVideos(Optional numberOfVideos); + + /** Clears the value of numberOfVideos field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearNumberOfVideos() { + return numberOfVideos(Optional.empty()); + } + /** * Setter for outputGcsUri. * @@ -143,6 +207,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("outputGcsUri") public abstract Builder outputGcsUri(String outputGcsUri); + @ExcludeFromGeneratedCoverageReport + abstract Builder outputGcsUri(Optional outputGcsUri); + + /** Clears the value of outputGcsUri field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearOutputGcsUri() { + return outputGcsUri(Optional.empty()); + } + /** * Setter for fps. * @@ -151,6 +225,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("fps") public abstract Builder fps(Integer fps); + @ExcludeFromGeneratedCoverageReport + abstract Builder fps(Optional fps); + + /** Clears the value of fps field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearFps() { + return fps(Optional.empty()); + } + /** * Setter for durationSeconds. * @@ -159,6 +243,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("durationSeconds") public abstract Builder durationSeconds(Integer durationSeconds); + @ExcludeFromGeneratedCoverageReport + abstract Builder durationSeconds(Optional durationSeconds); + + /** Clears the value of durationSeconds field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDurationSeconds() { + return durationSeconds(Optional.empty()); + } + /** * Setter for seed. * @@ -169,6 +263,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("seed") public abstract Builder seed(Integer seed); + @ExcludeFromGeneratedCoverageReport + abstract Builder seed(Optional seed); + + /** Clears the value of seed field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSeed() { + return seed(Optional.empty()); + } + /** * Setter for aspectRatio. * @@ -178,14 +282,34 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("aspectRatio") public abstract Builder aspectRatio(String aspectRatio); + @ExcludeFromGeneratedCoverageReport + abstract Builder aspectRatio(Optional aspectRatio); + + /** Clears the value of aspectRatio field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearAspectRatio() { + return aspectRatio(Optional.empty()); + } + /** * Setter for resolution. * - *

    resolution: The resolution for the generated video. 1280x720, 1920x1080 are supported. + *

    resolution: The resolution for the generated video. 720p and 1080p are supported. */ @JsonProperty("resolution") public abstract Builder resolution(String resolution); + @ExcludeFromGeneratedCoverageReport + abstract Builder resolution(Optional resolution); + + /** Clears the value of resolution field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResolution() { + return resolution(Optional.empty()); + } + /** * Setter for personGeneration. * @@ -195,6 +319,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("personGeneration") public abstract Builder personGeneration(String personGeneration); + @ExcludeFromGeneratedCoverageReport + abstract Builder personGeneration(Optional personGeneration); + + /** Clears the value of personGeneration field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPersonGeneration() { + return personGeneration(Optional.empty()); + } + /** * Setter for pubsubTopic. * @@ -203,15 +337,34 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("pubsubTopic") public abstract Builder pubsubTopic(String pubsubTopic); + @ExcludeFromGeneratedCoverageReport + abstract Builder pubsubTopic(Optional pubsubTopic); + + /** Clears the value of pubsubTopic field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPubsubTopic() { + return pubsubTopic(Optional.empty()); + } + /** * 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder negativePrompt(Optional negativePrompt); + + /** Clears the value of negativePrompt field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearNegativePrompt() { + return negativePrompt(Optional.empty()); + } + /** * Setter for enhancePrompt. * @@ -220,6 +373,16 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("enhancePrompt") public abstract Builder enhancePrompt(boolean enhancePrompt); + @ExcludeFromGeneratedCoverageReport + abstract Builder enhancePrompt(Optional enhancePrompt); + + /** Clears the value of enhancePrompt field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEnhancePrompt() { + return enhancePrompt(Optional.empty()); + } + /** * Setter for generateAudio. * @@ -228,10 +391,254 @@ public Builder httpOptions(HttpOptions.Builder httpOptionsBuilder) { @JsonProperty("generateAudio") public abstract Builder generateAudio(boolean generateAudio); + @ExcludeFromGeneratedCoverageReport + abstract Builder generateAudio(Optional generateAudio); + + /** Clears the value of generateAudio field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGenerateAudio() { + return generateAudio(Optional.empty()); + } + + /** + * Setter for lastFrame. + * + *

    lastFrame: Image to use as the last frame of generated videos. Only supported for image to + * video use cases. + */ + @JsonProperty("lastFrame") + public abstract Builder lastFrame(Image lastFrame); + + /** + * Setter for lastFrame builder. + * + *

    lastFrame: Image to use as the last frame of generated videos. Only supported for image to + * video use cases. + */ + @CanIgnoreReturnValue + public Builder lastFrame(Image.Builder lastFrameBuilder) { + return lastFrame(lastFrameBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder lastFrame(Optional lastFrame); + + /** Clears the value of lastFrame field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLastFrame() { + return lastFrame(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + 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. + */ + @CanIgnoreReturnValue + public Builder referenceImages( + VideoGenerationReferenceImage.Builder... referenceImagesBuilders) { + return referenceImages( + Arrays.asList(referenceImagesBuilders).stream() + .map(VideoGenerationReferenceImage.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder referenceImages(Optional> referenceImages); + + /** Clears the value of referenceImages field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearReferenceImages() { + return referenceImages(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder mask(VideoGenerationMask.Builder maskBuilder) { + return mask(maskBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder mask(Optional mask); + + /** Clears the value of mask field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMask() { + return mask(Optional.empty()); + } + + /** + * Setter for compressionQuality. + * + *

    compressionQuality: Compression quality of the generated videos. + */ + @JsonProperty("compressionQuality") + public abstract Builder compressionQuality(VideoCompressionQuality compressionQuality); + + @ExcludeFromGeneratedCoverageReport + abstract Builder compressionQuality(Optional compressionQuality); + + /** Clears the value of compressionQuality field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearCompressionQuality() { + return compressionQuality(Optional.empty()); + } + + /** + * Setter for compressionQuality given a known enum. + * + *

    compressionQuality: Compression quality of the generated videos. + */ + @CanIgnoreReturnValue + public Builder compressionQuality(VideoCompressionQuality.Known knownType) { + return compressionQuality(new VideoCompressionQuality(knownType)); + } + + /** + * Setter for compressionQuality given a string. + * + *

    compressionQuality: Compression quality of the generated videos. + */ + @CanIgnoreReturnValue + public Builder compressionQuality(String compressionQuality) { + return compressionQuality(new VideoCompressionQuality(compressionQuality)); + } + + /** + * Setter for labels. + * + *

    labels: User specified labels to track billing usage. + */ + @JsonProperty("labels") + public abstract Builder labels(Map labels); + + @ExcludeFromGeneratedCoverageReport + abstract Builder labels(Optional> labels); + + /** Clears the value of labels field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLabels() { + return labels(Optional.empty()); + } + + /** + * Setter for webhookConfig. + * + *

    webhookConfig: Webhook configuration for receiving notifications when the video generation + * operation completes. + */ + @JsonProperty("webhookConfig") + public abstract Builder webhookConfig(WebhookConfig webhookConfig); + + /** + * Setter for webhookConfig builder. + * + *

    webhookConfig: Webhook configuration for receiving notifications when the video generation + * operation completes. + */ + @CanIgnoreReturnValue + public Builder webhookConfig(WebhookConfig.Builder webhookConfigBuilder) { + return webhookConfig(webhookConfigBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder webhookConfig(Optional webhookConfig); + + /** Clears the value of webhookConfig field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearWebhookConfig() { + return webhookConfig(Optional.empty()); + } + + /** + * Setter for resizeMode. + * + *

    resizeMode: Resize mode of the image input for video generation. + */ + @JsonProperty("resizeMode") + public abstract Builder resizeMode(ImageResizeMode resizeMode); + + @ExcludeFromGeneratedCoverageReport + abstract Builder resizeMode(Optional resizeMode); + + /** Clears the value of resizeMode field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResizeMode() { + return resizeMode(Optional.empty()); + } + + /** + * Setter for resizeMode given a known enum. + * + *

    resizeMode: Resize mode of the image input for video generation. + */ + @CanIgnoreReturnValue + public Builder resizeMode(ImageResizeMode.Known knownType) { + return resizeMode(new ImageResizeMode(knownType)); + } + + /** + * Setter for resizeMode given a string. + * + *

    resizeMode: Resize mode of the image input for video generation. + */ + @CanIgnoreReturnValue + public Builder resizeMode(String resizeMode) { + return resizeMode(new ImageResizeMode(resizeMode)); + } + public abstract GenerateVideosConfig build(); } /** 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..98a80fe31aa 100644 --- a/src/main/java/com/google/genai/types/GenerateVideosOperation.java +++ b/src/main/java/com/google/genai/types/GenerateVideosOperation.java @@ -20,49 +20,41 @@ 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.errorprone.annotations.CanIgnoreReturnValue; 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(); } @@ -89,6 +81,16 @@ private static Builder create() { @JsonProperty("name") public abstract Builder name(String name); + @ExcludeFromGeneratedCoverageReport + abstract Builder name(Optional name); + + /** Clears the value of name field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearName() { + return name(Optional.empty()); + } + /** * Setter for metadata. * @@ -100,6 +102,16 @@ private static Builder create() { @JsonProperty("metadata") public abstract Builder metadata(Map metadata); + @ExcludeFromGeneratedCoverageReport + abstract Builder metadata(Optional> metadata); + + /** Clears the value of metadata field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMetadata() { + return metadata(Optional.empty()); + } + /** * Setter for done. * @@ -109,6 +121,16 @@ private static Builder create() { @JsonProperty("done") public abstract Builder done(boolean done); + @ExcludeFromGeneratedCoverageReport + abstract Builder done(Optional done); + + /** Clears the value of done field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearDone() { + return done(Optional.empty()); + } + /** * Setter for error. * @@ -117,6 +139,16 @@ private static Builder create() { @JsonProperty("error") public abstract Builder error(Map error); + @ExcludeFromGeneratedCoverageReport + abstract Builder error(Optional> error); + + /** Clears the value of error field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearError() { + return error(Optional.empty()); + } + /** * Setter for response. * @@ -130,14 +162,26 @@ private static Builder create() { * *

    response: The generated videos. */ + @CanIgnoreReturnValue public Builder response(GenerateVideosResponse.Builder responseBuilder) { return response(responseBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder response(Optional response); + + /** Clears the value of response field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearResponse() { + return response(Optional.empty()); + } + public abstract GenerateVideosOperation build(); } /** 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 719883572dd..0fbc4d25459 100644 --- a/src/main/java/com/google/genai/types/GenerateVideosParameters.java +++ b/src/main/java/com/google/genai/types/GenerateVideosParameters.java @@ -23,10 +23,11 @@ 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; -/** Class that represents the parameters for generating an image. */ +/** Class that represents the parameters for generating videos. */ @AutoValue @InternalApi @JsonDeserialize(builder = GenerateVideosParameters.Builder.class) @@ -38,19 +39,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 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 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); + @ExcludeFromGeneratedCoverageReport + abstract Builder prompt(Optional prompt); + + /** Clears the value of prompt field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPrompt() { + return prompt(Optional.empty()); + } + /** * Setter for image. * - *

    image: The input image for generating the videos. Optional if prompt 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); @@ -95,12 +132,82 @@ private static Builder create() { /** * Setter for image builder. * - *

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

    image: The input image for generating the videos. Optional if prompt is provided. Not + * allowed if video is provided. */ + @CanIgnoreReturnValue public Builder image(Image.Builder imageBuilder) { return image(imageBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder image(Optional image); + + /** Clears the value of image field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearImage() { + return image(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder video(Video.Builder videoBuilder) { + return video(videoBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder video(Optional

    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. + */ + @CanIgnoreReturnValue + public Builder source(GenerateVideosSource.Builder sourceBuilder) { + return source(sourceBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder source(Optional source); + + /** Clears the value of source field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSource() { + return source(Optional.empty()); + } + /** * Setter for config. * @@ -114,14 +221,26 @@ public Builder image(Image.Builder imageBuilder) { * *

    config: Configuration for generating videos. */ + @CanIgnoreReturnValue public Builder config(GenerateVideosConfig.Builder configBuilder) { return config(configBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder config(Optional config); + + /** Clears the value of config field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearConfig() { + return config(Optional.empty()); + } + public abstract GenerateVideosParameters build(); } /** 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..cc0ebc6fd4f 100644 --- a/src/main/java/com/google/genai/types/GenerateVideosResponse.java +++ b/src/main/java/com/google/genai/types/GenerateVideosResponse.java @@ -24,6 +24,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.Arrays; import java.util.List; @@ -46,6 +47,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(); } @@ -75,6 +77,7 @@ private static Builder create() { * *

    generatedVideos: List of the generated videos */ + @CanIgnoreReturnValue public Builder generatedVideos(GeneratedVideo... generatedVideos) { return generatedVideos(Arrays.asList(generatedVideos)); } @@ -84,6 +87,7 @@ public Builder generatedVideos(GeneratedVideo... generatedVideos) { * *

    generatedVideos: List of the generated videos */ + @CanIgnoreReturnValue public Builder generatedVideos(GeneratedVideo.Builder... generatedVideosBuilders) { return generatedVideos( Arrays.asList(generatedVideosBuilders).stream() @@ -91,6 +95,16 @@ public Builder generatedVideos(GeneratedVideo.Builder... generatedVideosBuilders .collect(toImmutableList())); } + @ExcludeFromGeneratedCoverageReport + abstract Builder generatedVideos(Optional> generatedVideos); + + /** Clears the value of generatedVideos field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearGeneratedVideos() { + return generatedVideos(Optional.empty()); + } + /** * Setter for raiMediaFilteredCount. * @@ -99,6 +113,16 @@ public Builder generatedVideos(GeneratedVideo.Builder... generatedVideosBuilders @JsonProperty("raiMediaFilteredCount") public abstract Builder raiMediaFilteredCount(Integer raiMediaFilteredCount); + @ExcludeFromGeneratedCoverageReport + abstract Builder raiMediaFilteredCount(Optional raiMediaFilteredCount); + + /** Clears the value of raiMediaFilteredCount field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearRaiMediaFilteredCount() { + return raiMediaFilteredCount(Optional.empty()); + } + /** * Setter for raiMediaFilteredReasons. * @@ -112,14 +136,26 @@ public Builder generatedVideos(GeneratedVideo.Builder... generatedVideosBuilders * *

    raiMediaFilteredReasons: Returns rai failure reasons if any. */ + @CanIgnoreReturnValue public Builder raiMediaFilteredReasons(String... raiMediaFilteredReasons) { return raiMediaFilteredReasons(Arrays.asList(raiMediaFilteredReasons)); } + @ExcludeFromGeneratedCoverageReport + abstract Builder raiMediaFilteredReasons(Optional> raiMediaFilteredReasons); + + /** Clears the value of raiMediaFilteredReasons field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearRaiMediaFilteredReasons() { + return raiMediaFilteredReasons(Optional.empty()); + } + public abstract GenerateVideosResponse build(); } /** 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..babb5924c9c --- /dev/null +++ b/src/main/java/com/google/genai/types/GenerateVideosSource.java @@ -0,0 +1,155 @@ +/* + * 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 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); + + @ExcludeFromGeneratedCoverageReport + abstract Builder prompt(Optional prompt); + + /** Clears the value of prompt field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearPrompt() { + return prompt(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder image(Image.Builder imageBuilder) { + return image(imageBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder image(Optional image); + + /** Clears the value of image field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearImage() { + return image(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder video(Video.Builder videoBuilder) { + return video(videoBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder video(Optional

    image: The output image data. */ + @CanIgnoreReturnValue public Builder image(Image.Builder imageBuilder) { return image(imageBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder image(Optional image); + + /** Clears the value of image field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearImage() { + return image(Optional.empty()); + } + /** * Setter for raiFilteredReason. * @@ -88,6 +101,16 @@ public Builder image(Image.Builder imageBuilder) { @JsonProperty("raiFilteredReason") public abstract Builder raiFilteredReason(String raiFilteredReason); + @ExcludeFromGeneratedCoverageReport + abstract Builder raiFilteredReason(Optional raiFilteredReason); + + /** Clears the value of raiFilteredReason field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearRaiFilteredReason() { + return raiFilteredReason(Optional.empty()); + } + /** * Setter for safetyAttributes. * @@ -103,10 +126,21 @@ public Builder image(Image.Builder imageBuilder) { *

    safetyAttributes: Safety attributes of the image. Lists of RAI categories and their scores * of each content. */ + @CanIgnoreReturnValue public Builder safetyAttributes(SafetyAttributes.Builder safetyAttributesBuilder) { return safetyAttributes(safetyAttributesBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder safetyAttributes(Optional safetyAttributes); + + /** Clears the value of safetyAttributes field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearSafetyAttributes() { + return safetyAttributes(Optional.empty()); + } + /** * Setter for enhancedPrompt. * @@ -116,10 +150,21 @@ public Builder safetyAttributes(SafetyAttributes.Builder safetyAttributesBuilder @JsonProperty("enhancedPrompt") public abstract Builder enhancedPrompt(String enhancedPrompt); + @ExcludeFromGeneratedCoverageReport + abstract Builder enhancedPrompt(Optional enhancedPrompt); + + /** Clears the value of enhancedPrompt field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearEnhancedPrompt() { + return enhancedPrompt(Optional.empty()); + } + public abstract GeneratedImage build(); } /** 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..5d5f441a66d --- /dev/null +++ b/src/main/java/com/google/genai/types/GeneratedImageMask.java @@ -0,0 +1,140 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 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.errorprone.annotations.CanIgnoreReturnValue; +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. + */ + @CanIgnoreReturnValue + public Builder mask(Image.Builder maskBuilder) { + return mask(maskBuilder.build()); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder mask(Optional mask); + + /** Clears the value of mask field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearMask() { + return mask(Optional.empty()); + } + + /** + * 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. + */ + @CanIgnoreReturnValue + public Builder labels(EntityLabel... labels) { + return labels(Arrays.asList(labels)); + } + + /** + * Setter for labels builder. + * + *

    labels: The detected entities on the segmented area. + */ + @CanIgnoreReturnValue + public Builder labels(EntityLabel.Builder... labelsBuilders) { + return labels( + Arrays.asList(labelsBuilders).stream() + .map(EntityLabel.Builder::build) + .collect(toImmutableList())); + } + + @ExcludeFromGeneratedCoverageReport + abstract Builder labels(Optional> labels); + + /** Clears the value of labels field. */ + @ExcludeFromGeneratedCoverageReport + @CanIgnoreReturnValue + public Builder clearLabels() { + return labels(Optional.empty()); + } + + 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..fd806eaa1cb 100644 --- a/src/main/java/com/google/genai/types/GeneratedVideo.java +++ b/src/main/java/com/google/genai/types/GeneratedVideo.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; @@ -34,6 +35,7 @@ public abstract class GeneratedVideo extends JsonSerializable { public abstract Optional

    video: The output video */ + @CanIgnoreReturnValue public Builder video(Video.Builder videoBuilder) { return video(videoBuilder.build()); } + @ExcludeFromGeneratedCoverageReport + abstract Builder video(Optional