diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94046873..a211506d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,29 +1,34 @@ name: CI on: push: - branches: - - main + branches-ignore: + - 'generated' + - 'codegen/**' + - 'integrated/**' + - 'stl-preview-head/**' + - 'stl-preview-base/**' pull_request: - branches: - - main - - next + branches-ignore: + - 'stl-preview-head/**' + - 'stl-preview-base/**' jobs: lint: + timeout-minutes: 15 name: lint - runs-on: ubuntu-latest - + runs-on: ${{ github.repository == 'stainless-sdks/hanzo-ai-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Set up Java - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: temurin java-version: | 8 - 17 + 21 cache: gradle - name: Set up Gradle @@ -31,20 +36,64 @@ jobs: - name: Run lints run: ./scripts/lint + + build: + timeout-minutes: 15 + name: build + permissions: + contents: read + id-token: write + runs-on: ${{ github.repository == 'stainless-sdks/hanzo-ai-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork + + steps: + - uses: actions/checkout@v6 + + - name: Set up Java + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: | + 8 + 21 + cache: gradle + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Build SDK + run: ./scripts/build + + - name: Get GitHub OIDC Token + if: github.repository == 'stainless-sdks/hanzo-ai-java' + id: github-oidc + uses: actions/github-script@v8 + with: + script: core.setOutput('github_token', await core.getIDToken()); + + - name: Build and upload Maven artifacts + if: github.repository == 'stainless-sdks/hanzo-ai-java' + env: + URL: https://pkg.stainless.com/s + AUTH: ${{ steps.github-oidc.outputs.github_token }} + SHA: ${{ github.sha }} + PROJECT: hanzo-ai-java + run: ./scripts/upload-artifacts test: + timeout-minutes: 15 name: test - runs-on: ubuntu-latest - + runs-on: ${{ github.repository == 'stainless-sdks/hanzo-ai-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Set up Java - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: temurin java-version: | 8 - 17 + 21 cache: gradle - name: Set up Gradle diff --git a/.github/workflows/publish-sonatype.yml b/.github/workflows/publish-sonatype.yml index 32aaa7ad..a89fe023 100644 --- a/.github/workflows/publish-sonatype.yml +++ b/.github/workflows/publish-sonatype.yml @@ -14,15 +14,15 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Set up Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v5 with: distribution: temurin java-version: | 8 - 17 + 21 cache: gradle - name: Set up Gradle @@ -33,7 +33,7 @@ jobs: export -- GPG_SIGNING_KEY_ID printenv -- GPG_SIGNING_KEY | gpg --batch --passphrase-fd 3 --import 3<<< "$GPG_SIGNING_PASSWORD" GPG_SIGNING_KEY_ID="$(gpg --with-colons --list-keys | awk -F : -- '/^pub:/ { getline; print "0x" substr($10, length($10) - 7) }')" - ./gradlew publishAndReleaseToMavenCentral --stacktrace -PmavenCentralUsername="$SONATYPE_USERNAME" -PmavenCentralPassword="$SONATYPE_PASSWORD" + ./gradlew publishAndReleaseToMavenCentral --stacktrace -PmavenCentralUsername="$SONATYPE_USERNAME" -PmavenCentralPassword="$SONATYPE_PASSWORD" --no-configuration-cache env: SONATYPE_USERNAME: ${{ secrets.HANZO_SONATYPE_USERNAME || secrets.SONATYPE_USERNAME }} SONATYPE_PASSWORD: ${{ secrets.HANZO_SONATYPE_PASSWORD || secrets.SONATYPE_PASSWORD }} diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index 6de875a6..272e3ac8 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -12,7 +12,7 @@ jobs: if: github.repository == 'hanzoai/java-sdk' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Check release environment run: | diff --git a/.gitignore b/.gitignore index 4e81838d..b1346e6d 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,6 @@ .gradle .idea .kotlin -build +build/ codegen.log kls_database.db diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f14b480a..aaf968a1 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.1.0-alpha.2" + ".": "0.1.0-alpha.3" } \ No newline at end of file diff --git a/.stats.yml b/.stats.yml index dbc44ca8..e829d1ef 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 188 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/hanzo-industries-inc%2FHanzo-AI-45310ce8b457cd9d29707322ab26acd87a4b64b286d9fe804bd7b23b89067b77.yml -openapi_spec_hash: fb26cd549e0fe94f333db686235564fd -config_hash: 830747463ff4d018b5633ce511e88558 +configured_endpoints: 187 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/hanzo-industries-inc%2Fhanzo-ai-971e209e1a47262e17483e5ac0d91e8013d10237ac89d6392ffabb5912ce83b9.yml +openapi_spec_hash: 029e800ed42f138d5b63bb4f40181c55 +config_hash: e927bafd76a1eace11894efc3517d245 diff --git a/CHANGELOG.md b/CHANGELOG.md index a34706be..cbd19834 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,79 @@ # Changelog +## 0.1.0-alpha.3 (2026-01-26) + +Full Changelog: [v0.1.0-alpha.2...v0.1.0-alpha.3](https://github.com/hanzoai/java-sdk/compare/v0.1.0-alpha.2...v0.1.0-alpha.3) + +### ⚠ BREAKING CHANGES + +* **client:** extract auto pagination to shared classes +* **client:** **Migration:** - If you were referencing the `AutoPager` class on a specific `*Page` or `*PageAsync` type, then you should instead reference the shared `AutoPager` and `AutoPagerAsync` types, under the `core` package + - `AutoPagerAsync` now has different usage. You can call `.subscribe(...)` on the returned object instead to get called back each page item. You can also call `onCompleteFuture()` to get a future that completes when all items have been processed. Finally, you can call `.close()` on the returned object to stop auto-paginating early + - If you were referencing `getNextPage` or `getNextPageParams`: + - Swap to `nextPage()` and `nextPageParams()` + - Note that these both now return non-optional types (use `hasNextPage()` before calling these, since they will throw if it's impossible to get another page) + +### Features + +* **api:** api update ([589ce7a](https://github.com/hanzoai/java-sdk/commit/589ce7af97f7b1fcea2519ae75f184ea7a6529ff)) +* **api:** api update ([5997aeb](https://github.com/hanzoai/java-sdk/commit/5997aeb3a12a1dbb0e628c3ae2e2b73d6f5c0391)) +* **api:** api update ([bb22539](https://github.com/hanzoai/java-sdk/commit/bb225395cd286571c72d6ad48582d0f5b54b9db9)) +* **api:** api update ([#9](https://github.com/hanzoai/java-sdk/issues/9)) ([a0ab87a](https://github.com/hanzoai/java-sdk/commit/a0ab87ace8769fc2320a22cf1bd2d259ede567ae)) +* **client:** add enum validation method ([ebf7b97](https://github.com/hanzoai/java-sdk/commit/ebf7b9734d07621d28d394281160823dea9c8de3)) +* **client:** allow providing some params positionally ([4f35e18](https://github.com/hanzoai/java-sdk/commit/4f35e180123ecba96578a2eab86af922115cd005)) +* **client:** expose request body setter and getter ([#16](https://github.com/hanzoai/java-sdk/issues/16)) ([69c2c6c](https://github.com/hanzoai/java-sdk/commit/69c2c6cd26d41cd1e0a5012398cd8ba54a7617ca)) +* **client:** extract auto pagination to shared classes ([e735ee9](https://github.com/hanzoai/java-sdk/commit/e735ee9fb131714101989c4d8a724399932e8026)) +* **client:** make datetime deserialization more lenient ([#15](https://github.com/hanzoai/java-sdk/issues/15)) ([d1cf89d](https://github.com/hanzoai/java-sdk/commit/d1cf89db05f61aa38c0a8d274ba3ee77d17e0341)) +* **client:** make union deserialization more robust ([#14](https://github.com/hanzoai/java-sdk/issues/14)) ([ebf7b97](https://github.com/hanzoai/java-sdk/commit/ebf7b9734d07621d28d394281160823dea9c8de3)) +* **client:** support setting base URL via env var ([7b40d13](https://github.com/hanzoai/java-sdk/commit/7b40d13ad642b0db4f872cf54cb0e75a8fb5fc1c)) + + +### Bug Fixes + +* **client:** add missing convenience methods ([afd652a](https://github.com/hanzoai/java-sdk/commit/afd652a14b550ae68fc192379c2649f3dea63601)) +* **client:** bump to better jackson version ([21f5b79](https://github.com/hanzoai/java-sdk/commit/21f5b79e8a12fb75bb6ea91fc46173f4fed1fc8f)) +* **client:** don't call `validate()` during deserialization if we don't have to ([#11](https://github.com/hanzoai/java-sdk/issues/11)) ([e5af84a](https://github.com/hanzoai/java-sdk/commit/e5af84a40d2f50556adcb9b54d088ff4482c81c7)) +* **client:** limit json deserialization coercion ([#12](https://github.com/hanzoai/java-sdk/issues/12)) ([a476286](https://github.com/hanzoai/java-sdk/commit/a4762869b0ad34a0212ed4ea2fc00cce3a020487)) +* **client:** return `Optional<T>` instead of `Optional` ([#19](https://github.com/hanzoai/java-sdk/issues/19)) ([becb670](https://github.com/hanzoai/java-sdk/commit/becb670d92fab9e105289da811f8b2ce3c63d776)) +* pluralize `list` response variables ([#13](https://github.com/hanzoai/java-sdk/issues/13)) ([a7a0b4a](https://github.com/hanzoai/java-sdk/commit/a7a0b4a6b847da6df6b459af2c149c7569ad9e0c)) + + +### Performance Improvements + +* **client:** cached parsed type in `HttpResponseFor` ([#17](https://github.com/hanzoai/java-sdk/issues/17)) ([91c37b1](https://github.com/hanzoai/java-sdk/commit/91c37b152243864b852b3ab04c05ab0aadf28912)) +* **internal:** improve compilation+test speed ([668e12a](https://github.com/hanzoai/java-sdk/commit/668e12a649f917543d6a44810cdce0f035993afe)) + + +### Chores + +* **ci:** add timeout thresholds for CI jobs ([2711202](https://github.com/hanzoai/java-sdk/commit/271120209107485ef828f66150c6b32c14db9d2f)) +* **ci:** only use depot for staging repos ([76c8fa1](https://github.com/hanzoai/java-sdk/commit/76c8fa1b7cc7a685bbc0326773579dee3120a678)) +* **client:** remove unnecessary json state from some query param classes ([ebf7b97](https://github.com/hanzoai/java-sdk/commit/ebf7b9734d07621d28d394281160823dea9c8de3)) +* configure new SDK language ([4e8ff89](https://github.com/hanzoai/java-sdk/commit/4e8ff890138cf98a46038bf5ca5484820136929a)) +* **docs:** grammar improvements ([ccd164e](https://github.com/hanzoai/java-sdk/commit/ccd164eaddd08e28deb6dc7934e27b75febee968)) +* **internal:** add invalid json deserialization tests ([ebf7b97](https://github.com/hanzoai/java-sdk/commit/ebf7b9734d07621d28d394281160823dea9c8de3)) +* **internal:** add json roundtripping tests ([ebf7b97](https://github.com/hanzoai/java-sdk/commit/ebf7b9734d07621d28d394281160823dea9c8de3)) +* **internal:** codegen related update ([f5151f7](https://github.com/hanzoai/java-sdk/commit/f5151f714c25e8331f9da13e5f3cf0169d2c1bd5)) +* **internal:** codegen related update ([0b6be6f](https://github.com/hanzoai/java-sdk/commit/0b6be6fc53010ddef052f0142400aa2599225a26)) +* **internal:** expand CI branch coverage ([1eddeb1](https://github.com/hanzoai/java-sdk/commit/1eddeb17b64eb80f6db6969d181c8f48ec9a08a6)) +* **internal:** java 17 -> 21 on ci ([2bcbac5](https://github.com/hanzoai/java-sdk/commit/2bcbac55db86820f67047c1be46898513970bee8)) +* **internal:** reduce CI branch coverage ([c8a88d7](https://github.com/hanzoai/java-sdk/commit/c8a88d7303cd41aada70dea065bb8a51522c3373)) +* **internal:** remove flaky `-Xbackend-threads=0` option ([2548d25](https://github.com/hanzoai/java-sdk/commit/2548d2575aaab0c2dbcf87b9df3e9d04cd2f9f25)) +* **internal:** swap from `getNullable` to `getOptional` ([#18](https://github.com/hanzoai/java-sdk/issues/18)) ([b4a0c8b](https://github.com/hanzoai/java-sdk/commit/b4a0c8b295e7216dd22f472b4ee4198664f7dad0)) +* **internal:** update java toolchain ([5c62cf3](https://github.com/hanzoai/java-sdk/commit/5c62cf3a190d7fc3d2c0def9b589c7dceb0bb025)) +* **internal:** use `byteInputStream()` in tests ([afd652a](https://github.com/hanzoai/java-sdk/commit/afd652a14b550ae68fc192379c2649f3dea63601)) + + +### Documentation + +* add comments to `JsonField` classes ([becb670](https://github.com/hanzoai/java-sdk/commit/becb670d92fab9e105289da811f8b2ce3c63d776)) +* **client:** update jackson compat error message ([b2310d3](https://github.com/hanzoai/java-sdk/commit/b2310d32ce73c02a5942f04fbfc66d38c6c371d7)) +* document how to forcibly omit required field ([4dc5520](https://github.com/hanzoai/java-sdk/commit/4dc5520842ee6f01676aa386177d8924430fc3fa)) +* explain http client customization ([e43d638](https://github.com/hanzoai/java-sdk/commit/e43d6381ec86c1c7372e03fede163b2bd4fa673a)) +* explain jackson compat in readme ([b62faed](https://github.com/hanzoai/java-sdk/commit/b62faed4882e4f2a39014a11fda5297c09269a07)) +* swap examples used in readme ([#20](https://github.com/hanzoai/java-sdk/issues/20)) ([4dc5520](https://github.com/hanzoai/java-sdk/commit/4dc5520842ee6f01676aa386177d8924430fc3fa)) +* update documentation links to be more uniform ([c878297](https://github.com/hanzoai/java-sdk/commit/c878297f959b3215eacb52b1579d4dc0eae1f79b)) + ## 0.1.0-alpha.2 (2025-03-27) Full Changelog: [v0.1.0-alpha.1...v0.1.0-alpha.2](https://github.com/hanzoai/java-sdk/compare/v0.1.0-alpha.1...v0.1.0-alpha.2) diff --git a/LICENSE b/LICENSE index 614d2f02..ff91a2c8 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2025 Hanzo + Copyright 2026 Hanzo Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index f4d674b8..54ce185a 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ -[![Maven Central](https://img.shields.io/maven-central/v/ai.hanzo.api/hanzo-java)](https://central.sonatype.com/artifact/ai.hanzo.api/hanzo-java/0.1.0-alpha.2) -[![javadoc](https://javadoc.io/badge2/ai.hanzo.api/hanzo-java/0.1.0-alpha.2/javadoc.svg)](https://javadoc.io/doc/ai.hanzo.api/hanzo-java/0.1.0-alpha.2) +[![Maven Central](https://img.shields.io/maven-central/v/ai.hanzo.api/hanzo-java)](https://central.sonatype.com/artifact/ai.hanzo.api/hanzo-java/0.1.0-alpha.3) +[![javadoc](https://javadoc.io/badge2/ai.hanzo.api/hanzo-java/0.1.0-alpha.3/javadoc.svg)](https://javadoc.io/doc/ai.hanzo.api/hanzo-java/0.1.0-alpha.3) @@ -13,9 +13,18 @@ The Hanzo Java SDK is similar to the Hanzo Kotlin SDK but with minor differences It is generated with [Stainless](https://www.stainless.com/). +## MCP Server + +Use the Hanzo MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application. + +[![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en-US/install-mcp?name=hanzoai-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImhhbnpvYWktbWNwIl19) +[![Install in VS Code](https://img.shields.io/badge/_-Add_to_VS_Code-blue?style=for-the-badge&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCA0MCA0MCI+PHBhdGggZmlsbD0iI0VFRSIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNMzAuMjM1IDM5Ljg4NGEyLjQ5MSAyLjQ5MSAwIDAgMS0xLjc4MS0uNzNMMTIuNyAyNC43OGwtMy40NiAyLjYyNC0zLjQwNiAyLjU4MmExLjY2NSAxLjY2NSAwIDAgMS0xLjA4Mi4zMzggMS42NjQgMS42NjQgMCAwIDEtMS4wNDYtLjQzMWwtMi4yLTJhMS42NjYgMS42NjYgMCAwIDEgMC0yLjQ2M0w3LjQ1OCAyMCA0LjY3IDE3LjQ1MyAxLjUwNyAxNC41N2ExLjY2NSAxLjY2NSAwIDAgMSAwLTIuNDYzbDIuMi0yYTEuNjY1IDEuNjY1IDAgMCAxIDIuMTMtLjA5N2w2Ljg2MyA1LjIwOUwyOC40NTIuODQ0YTIuNDg4IDIuNDg4IDAgMCAxIDEuODQxLS43MjljLjM1MS4wMDkuNjk5LjA5MSAxLjAxOS4yNDVsOC4yMzYgMy45NjFhMi41IDIuNSAwIDAgMSAxLjQxNSAyLjI1M3YuMDk5LS4wNDVWMzMuMzd2LS4wNDUuMDk1YTIuNTAxIDIuNTAxIDAgMCAxLTEuNDE2IDIuMjU3bC04LjIzNSAzLjk2MWEyLjQ5MiAyLjQ5MiAwIDAgMS0xLjA3Ny4yNDZabS43MTYtMjguOTQ3LTExLjk0OCA5LjA2MiAxMS45NTIgOS4wNjUtLjAwNC0xOC4xMjdaIi8+PC9zdmc+)](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22hanzoai-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22hanzoai-mcp%22%5D%7D) + +> Note: You may need to set environment variables in your MCP client. + -The REST API documentation can be found on [docs.hanzo.ai](https://docs.hanzo.ai). Javadocs are also available on [javadoc.io](https://javadoc.io/doc/ai.hanzo.api/hanzo-java/0.1.0-alpha.2). +The REST API documentation can be found on [docs.hanzo.ai](https://docs.hanzo.ai). Javadocs are available on [javadoc.io](https://javadoc.io/doc/ai.hanzo.api/hanzo-java/0.1.0-alpha.3). @@ -26,7 +35,7 @@ The REST API documentation can be found on [docs.hanzo.ai](https://docs.hanzo.ai ### Gradle ```kotlin -implementation("ai.hanzo.api:hanzo-java:0.1.0-alpha.2") +implementation("ai.hanzo.api:hanzo-java:0.1.0-alpha.3") ``` ### Maven @@ -35,7 +44,7 @@ implementation("ai.hanzo.api:hanzo-java:0.1.0-alpha.2") ai.hanzo.api hanzo-java - 0.1.0-alpha.2 + 0.1.0-alpha.3 ``` @@ -53,7 +62,8 @@ import ai.hanzo.api.client.okhttp.HanzoOkHttpClient; import ai.hanzo.api.models.ClientGetHomeParams; import ai.hanzo.api.models.ClientGetHomeResponse; -// Configures using the `HANZO_API_KEY` environment variable +// Configures using the `hanzo.apiKey` and `hanzo.baseUrl` system properties +// Or configures using the `HANZO_API_KEY` and `HANZO_BASE_URL` environment variables HanzoClient client = HanzoOkHttpClient.fromEnv(); ClientGetHomeResponse response = client.getHome(); @@ -61,13 +71,14 @@ ClientGetHomeResponse response = client.getHome(); ## Client configuration -Configure the client using environment variables: +Configure the client using system properties or environment variables: ```java import ai.hanzo.api.client.HanzoClient; import ai.hanzo.api.client.okhttp.HanzoOkHttpClient; -// Configures using the `HANZO_API_KEY` environment variable +// Configures using the `hanzo.apiKey` and `hanzo.baseUrl` system properties +// Or configures using the `HANZO_API_KEY` and `HANZO_BASE_URL` environment variables HanzoClient client = HanzoOkHttpClient.fromEnv(); ``` @@ -89,7 +100,8 @@ import ai.hanzo.api.client.HanzoClient; import ai.hanzo.api.client.okhttp.HanzoOkHttpClient; HanzoClient client = HanzoOkHttpClient.builder() - // Configures using the `HANZO_API_KEY` environment variable + // Configures using the `hanzo.apiKey` and `hanzo.baseUrl` system properties + // Or configures using the `HANZO_API_KEY` and `HANZO_BASE_URL` environment variables .fromEnv() .apiKey("My API Key") .build(); @@ -97,14 +109,32 @@ HanzoClient client = HanzoOkHttpClient.builder() See this table for the available options: -| Setter | Environment variable | Required | Default value | -| -------- | -------------------- | -------- | ------------- | -| `apiKey` | `HANZO_API_KEY` | true | - | +| Setter | System property | Environment variable | Required | Default value | +| --------- | --------------- | -------------------- | -------- | ------------------------ | +| `apiKey` | `hanzo.apiKey` | `HANZO_API_KEY` | true | - | +| `baseUrl` | `hanzo.baseUrl` | `HANZO_BASE_URL` | true | `"https://api.hanzo.ai"` | + +System properties take precedence over environment variables. > [!TIP] > Don't create more than one client in the same application. Each client has a connection pool and > thread pools, which are more efficient to share between requests. +### Modifying configuration + +To temporarily use a modified client configuration, while reusing the same connection and thread pools, call `withOptions()` on any client or service: + +```java +import ai.hanzo.api.client.HanzoClient; + +HanzoClient clientWithOptions = client.withOptions(optionsBuilder -> { + optionsBuilder.baseUrl("https://example.com"); + optionsBuilder.maxRetries(42); +}); +``` + +The `withOptions()` method does not affect the original client or service. + ## Requests and responses To send a request to the Hanzo API, build an instance of some `Params` class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Java class. @@ -130,7 +160,8 @@ import ai.hanzo.api.models.ClientGetHomeParams; import ai.hanzo.api.models.ClientGetHomeResponse; import java.util.concurrent.CompletableFuture; -// Configures using the `HANZO_API_KEY` environment variable +// Configures using the `hanzo.apiKey` and `hanzo.baseUrl` system properties +// Or configures using the `HANZO_API_KEY` and `HANZO_BASE_URL` environment variables HanzoClient client = HanzoOkHttpClient.fromEnv(); CompletableFuture response = client.async().getHome(); @@ -145,7 +176,8 @@ import ai.hanzo.api.models.ClientGetHomeParams; import ai.hanzo.api.models.ClientGetHomeResponse; import java.util.concurrent.CompletableFuture; -// Configures using the `HANZO_API_KEY` environment variable +// Configures using the `hanzo.apiKey` and `hanzo.baseUrl` system properties +// Or configures using the `HANZO_API_KEY` and `HANZO_BASE_URL` environment variables HanzoClientAsync client = HanzoOkHttpClientAsync.fromEnv(); CompletableFuture response = client.getHome(); @@ -258,6 +290,8 @@ The SDK throws custom unchecked exception types: - [`HanzoIoException`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/errors/HanzoIoException.kt): I/O networking errors. +- [`HanzoRetryableException`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/errors/HanzoRetryableException.kt): Generic error indicating a failure that could be retried by the client. + - [`HanzoInvalidDataException`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/errors/HanzoInvalidDataException.kt): Failure to interpret successfully parsed data. For example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it from the response. - [`HanzoException`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/errors/HanzoException.kt): Base class for all exceptions. Most errors will result in one of the previously mentioned ones, but completely generic errors may be thrown using the base class. @@ -269,20 +303,39 @@ The SDK uses the standard [OkHttp logging interceptor](https://github.com/square Enable logging by setting the `HANZO_LOG` environment variable to `info`: ```sh -$ export HANZO_LOG=info +export HANZO_LOG=info ``` Or to `debug` for more verbose logging: ```sh -$ export HANZO_LOG=debug +export HANZO_LOG=debug ``` +## ProGuard and R8 + +Although the SDK uses reflection, it is still usable with [ProGuard](https://github.com/Guardsquare/proguard) and [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization) because `hanzo-java-core` is published with a [configuration file](hanzo-java-core/src/main/resources/META-INF/proguard/hanzo-java-core.pro) containing [keep rules](https://www.guardsquare.com/manual/configuration/usage). + +ProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary. + +## Jackson + +The SDK depends on [Jackson](https://github.com/FasterXML/jackson) for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default. + +The SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config). + +If the SDK threw an exception, but you're _certain_ the version is compatible, then disable the version check using the `checkJacksonVersionCompatibility` on [`HanzoOkHttpClient`](hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClient.kt) or [`HanzoOkHttpClientAsync`](hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClientAsync.kt). + +> [!CAUTION] +> We make no guarantee that the SDK works correctly when the Jackson version check is disabled. + +Also note that there are bugs in older Jackson versions that can affect the SDK. We don't work around all Jackson bugs ([example](https://github.com/FasterXML/jackson-databind/issues/3240)) and expect users to upgrade Jackson for those instead. + ## Network options ### Retries -The SDK automatically retries 2 times by default, with a short exponential backoff. +The SDK automatically retries 2 times by default, with a short exponential backoff between requests. Only the following error types are retried: @@ -292,7 +345,7 @@ Only the following error types are retried: - 429 Rate Limit - 5xx Internal -The API may also explicitly instruct the SDK to retry or not retry a response. +The API may also explicitly instruct the SDK to retry or not retry a request. To set a custom number of retries, configure the client using the `maxRetries` method: @@ -313,7 +366,6 @@ Requests time out after 1 minute by default. To set a custom timeout, configure the method call using the `timeout` method: ```java -import ai.hanzo.api.models.ClientGetHomeParams; import ai.hanzo.api.models.ClientGetHomeResponse; ClientGetHomeResponse response = client.getHome(RequestOptions.builder().timeout(Duration.ofSeconds(30)).build()); @@ -352,6 +404,27 @@ HanzoClient client = HanzoOkHttpClient.builder() .build(); ``` +### HTTPS + +> [!NOTE] +> Most applications should not call these methods, and instead use the system defaults. The defaults include +> special optimizations that can be lost if the implementations are modified. + +To configure how HTTPS connections are secured, configure the client using the `sslSocketFactory`, `trustManager`, and `hostnameVerifier` methods: + +```java +import ai.hanzo.api.client.HanzoClient; +import ai.hanzo.api.client.okhttp.HanzoOkHttpClient; + +HanzoClient client = HanzoOkHttpClient.builder() + .fromEnv() + // If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa. + .sslSocketFactory(yourSSLSocketFactory) + .trustManager(yourTrustManager) + .hostnameVerifier(yourHostnameVerifier) + .build(); +``` + ### Environments The SDK sends requests to the production by default. To send requests to a different environment, configure the client like so: @@ -366,6 +439,42 @@ HanzoClient client = HanzoOkHttpClient.builder() .build(); ``` +### Custom HTTP client + +The SDK consists of three artifacts: + +- `hanzo-java-core` + - Contains core SDK logic + - Does not depend on [OkHttp](https://square.github.io/okhttp) + - Exposes [`HanzoClient`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClient.kt), [`HanzoClientAsync`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsync.kt), [`HanzoClientImpl`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientImpl.kt), and [`HanzoClientAsyncImpl`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsyncImpl.kt), all of which can work with any HTTP client +- `hanzo-java-client-okhttp` + - Depends on [OkHttp](https://square.github.io/okhttp) + - Exposes [`HanzoOkHttpClient`](hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClient.kt) and [`HanzoOkHttpClientAsync`](hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClientAsync.kt), which provide a way to construct [`HanzoClientImpl`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientImpl.kt) and [`HanzoClientAsyncImpl`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsyncImpl.kt), respectively, using OkHttp +- `hanzo-java` + - Depends on and exposes the APIs of both `hanzo-java-core` and `hanzo-java-client-okhttp` + - Does not have its own logic + +This structure allows replacing the SDK's default HTTP client without pulling in unnecessary dependencies. + +#### Customized [`OkHttpClient`](https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html) + +> [!TIP] +> Try the available [network options](#network-options) before replacing the default client. + +To use a customized `OkHttpClient`: + +1. Replace your [`hanzo-java` dependency](#installation) with `hanzo-java-core` +2. Copy `hanzo-java-client-okhttp`'s [`OkHttpClient`](hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/OkHttpClient.kt) class into your code and customize it +3. Construct [`HanzoClientImpl`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientImpl.kt) or [`HanzoClientAsyncImpl`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsyncImpl.kt), similarly to [`HanzoOkHttpClient`](hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClient.kt) or [`HanzoOkHttpClientAsync`](hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClientAsync.kt), using your customized client + +### Completely custom HTTP client + +To use a completely custom HTTP client: + +1. Replace your [`hanzo-java` dependency](#installation) with `hanzo-java-core` +2. Write a class that implements the [`HttpClient`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/HttpClient.kt) interface +3. Construct [`HanzoClientImpl`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientImpl.kt) or [`HanzoClientAsyncImpl`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsyncImpl.kt), similarly to [`HanzoOkHttpClient`](hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClient.kt) or [`HanzoOkHttpClientAsync`](hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClientAsync.kt), using your new client class + ## Undocumented API functionality The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API. @@ -394,7 +503,7 @@ import ai.hanzo.api.core.JsonValue; import ai.hanzo.api.models.model.ModelCreateParams; ModelCreateParams params = ModelCreateParams.builder() - .llmParams(ModelCreateParams.LlmParams.builder() + .litellmParams(ModelCreateParams.LitellmParams.builder() .putAdditionalProperty("secretProperty", JsonValue.from("42")) .build()) .build(); @@ -449,6 +558,20 @@ JsonValue complexValue = JsonValue.from(Map.of( )); ``` +Normally a `Builder` class's `build` method will throw [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html) if any required parameter or property is unset. + +To forcibly omit a required parameter or property, pass [`JsonMissing`](hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Values.kt): + +```java +import ai.hanzo.api.core.JsonMissing; +import ai.hanzo.api.models.ClientGetHomeParams; +import ai.hanzo.api.models.openai.OpenAICreateParams; + +ClientGetHomeParams params = OpenAICreateParams.builder() + .endpoint(JsonMissing.of()) + .build(); +``` + ### Response properties To access undocumented response properties, call the `_additionalProperties()` method: @@ -520,7 +643,6 @@ UtilTokenCounterResponse response = client.utils().tokenCounter(params).validate Or configure the method call to validate the response using the `responseValidation` method: ```java -import ai.hanzo.api.models.ClientGetHomeParams; import ai.hanzo.api.models.ClientGetHomeResponse; ClientGetHomeResponse response = client.getHome(RequestOptions.builder().responseValidation(true).build()); diff --git a/SECURITY.md b/SECURITY.md index bada7faa..0b579e02 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -16,11 +16,11 @@ before making any information public. ## Reporting Non-SDK Related Security Issues If you encounter security issues that are not directly related to SDKs but pertain to the services -or products provided by Hanzo please follow the respective company's security reporting guidelines. +or products provided by Hanzo, please follow the respective company's security reporting guidelines. ### Hanzo Terms and Policies -Please contact dev@hanzo.ai for any questions or concerns regarding security of our services. +Please contact dev@hanzo.ai for any questions or concerns regarding the security of our services. --- diff --git a/bin/check-release-environment b/bin/check-release-environment index 8f014071..3a6a7b4a 100644 --- a/bin/check-release-environment +++ b/bin/check-release-environment @@ -3,19 +3,19 @@ errors=() if [ -z "${SONATYPE_USERNAME}" ]; then - errors+=("The HANZO_SONATYPE_USERNAME secret has not been set. Please set it in either this repository's secrets or your organization secrets") + errors+=("The SONATYPE_USERNAME secret has not been set. Please set it in either this repository's secrets or your organization secrets") fi if [ -z "${SONATYPE_PASSWORD}" ]; then - errors+=("The HANZO_SONATYPE_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") + errors+=("The SONATYPE_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") fi if [ -z "${GPG_SIGNING_KEY}" ]; then - errors+=("The HANZO_SONATYPE_GPG_SIGNING_KEY secret has not been set. Please set it in either this repository's secrets or your organization secrets") + errors+=("The GPG_SIGNING_KEY secret has not been set. Please set it in either this repository's secrets or your organization secrets") fi if [ -z "${GPG_SIGNING_PASSWORD}" ]; then - errors+=("The HANZO_SONATYPE_GPG_SIGNING_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") + errors+=("The GPG_SIGNING_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") fi lenErrors=${#errors[@]} diff --git a/build.gradle.kts b/build.gradle.kts index 65121943..83d42120 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -8,7 +8,20 @@ repositories { allprojects { group = "ai.hanzo.api" - version = "0.1.0-alpha.2" // x-release-please-version + version = "0.1.0-alpha.3" // x-release-please-version +} + +subprojects { + // These are populated with dependencies by `buildSrc` scripts. + tasks.register("format") { + group = "Verification" + description = "Formats all source files." + } + tasks.register("lint") { + group = "Verification" + description = "Verifies all source files are formatted." + } + apply(plugin = "org.jetbrains.dokka") } subprojects { diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 778c89de..c6dc92ec 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -10,7 +10,6 @@ repositories { } dependencies { - implementation("com.diffplug.spotless:spotless-plugin-gradle:7.0.2") implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.20") implementation("com.vanniktech:gradle-maven-publish-plugin:0.28.0") } diff --git a/buildSrc/src/main/kotlin/hanzo.java.gradle.kts b/buildSrc/src/main/kotlin/hanzo.java.gradle.kts index e39d9ac6..70fc33f4 100644 --- a/buildSrc/src/main/kotlin/hanzo.java.gradle.kts +++ b/buildSrc/src/main/kotlin/hanzo.java.gradle.kts @@ -1,27 +1,16 @@ -import com.diffplug.gradle.spotless.SpotlessExtension import org.gradle.api.tasks.testing.logging.TestExceptionFormat plugins { `java-library` - id("com.diffplug.spotless") } repositories { mavenCentral() } -configure { - java { - importOrder() - removeUnusedImports() - palantirJavaFormat() - toggleOffOn() - } -} - java { toolchain { - languageVersion.set(JavaLanguageVersion.of(17)) + languageVersion.set(JavaLanguageVersion.of(21)) } sourceCompatibility = JavaVersion.VERSION_1_8 @@ -53,3 +42,86 @@ tasks.withType().configureEach { exceptionFormat = TestExceptionFormat.FULL } } + +val palantir by configurations.creating +dependencies { + palantir("com.palantir.javaformat:palantir-java-format:2.73.0") +} + +fun registerPalantir( + name: String, + description: String, +) { + val javaName = "${name}Java" + tasks.register(javaName) { + group = "Verification" + this.description = description + + classpath = palantir + mainClass = "com.palantir.javaformat.java.Main" + + // Avoid an `IllegalAccessError` on Java 9+. + jvmArgs( + "--add-exports", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED", + ) + + // Use paths relative to the current module. + val argumentFile = + project.layout.buildDirectory.file("palantir-$name-args.txt").get().asFile + val lastRunTimeFile = + project.layout.buildDirectory.file("palantir-$name-last-run.txt").get().asFile + + // Read the time when this task was last executed for this module (if ever). + val lastRunTime = lastRunTimeFile.takeIf { it.exists() }?.readText()?.toLongOrNull() ?: 0L + + // Use a `fileTree` relative to the module's source directory. + val javaFiles = project.fileTree("src") { include("**/*.java") } + + // Determine if any files need to be formatted or linted and continue only if there is at least + // one file. + onlyIf { javaFiles.any { it.lastModified() > lastRunTime } } + + inputs.files(javaFiles) + + doFirst { + // Create the argument file and set the preferred formatting style. + argumentFile.parentFile.mkdirs() + argumentFile.writeText("--palantir\n") + + if (name == "lint") { + // For lint, do a dry run, so no files are modified. Set the exit code to 1 (instead of + // the default 0) if any files need to be formatted, indicating that linting has failed. + argumentFile.appendText("--dry-run\n") + argumentFile.appendText("--set-exit-if-changed\n") + } else { + // `--dry-run` and `--replace` (for in-place formatting) are mutually exclusive. + argumentFile.appendText("--replace\n") + } + + // Write the modified files to the argument file. + javaFiles.filter { it.lastModified() > lastRunTime } + .forEach { argumentFile.appendText("${it.absolutePath}\n") } + } + + doLast { + // Record the last execution time for later up-to-date checking. + lastRunTimeFile.writeText(System.currentTimeMillis().toString()) + } + + // Pass the argument file using the @ symbol + args = listOf("@${argumentFile.absolutePath}") + + outputs.upToDateWhen { javaFiles.none { it.lastModified() > lastRunTime } } + } + + tasks.named(name) { + dependsOn(tasks.named(javaName)) + } +} + +registerPalantir(name = "format", description = "Formats all Java source files.") +registerPalantir(name = "lint", description = "Verifies all Java source files are formatted.") diff --git a/buildSrc/src/main/kotlin/hanzo.kotlin.gradle.kts b/buildSrc/src/main/kotlin/hanzo.kotlin.gradle.kts index 3f7ee106..fc8f35d8 100644 --- a/buildSrc/src/main/kotlin/hanzo.kotlin.gradle.kts +++ b/buildSrc/src/main/kotlin/hanzo.kotlin.gradle.kts @@ -1,4 +1,3 @@ -import com.diffplug.gradle.spotless.SpotlessExtension import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.dsl.KotlinVersion @@ -7,9 +6,13 @@ plugins { kotlin("jvm") } +repositories { + mavenCentral() +} + kotlin { jvmToolchain { - languageVersion.set(JavaLanguageVersion.of(17)) + languageVersion.set(JavaLanguageVersion.of(21)) } compilerOptions { @@ -27,15 +30,80 @@ kotlin { } } -configure { - kotlin { - ktfmt().kotlinlangStyle() - toggleOffOn() - } +tasks.withType().configureEach { + systemProperty("junit.jupiter.execution.parallel.enabled", true) + systemProperty("junit.jupiter.execution.parallel.mode.default", "concurrent") + + // `SKIP_MOCK_TESTS` affects which tests run so it must be added as input for proper cache invalidation. + inputs.property("skipMockTests", System.getenv("SKIP_MOCK_TESTS")).optional(true) } -// Run tests in parallel to some degree. -tasks.withType().configureEach { - maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceAtLeast(1) - forkEvery = 100 +val ktfmt by configurations.creating +dependencies { + ktfmt("com.facebook:ktfmt:0.56") +} + +fun registerKtfmt( + name: String, + description: String, +) { + val kotlinName = "${name}Kotlin" + tasks.register(kotlinName) { + group = "Verification" + this.description = description + + classpath = ktfmt + mainClass = "com.facebook.ktfmt.cli.Main" + + // Use paths relative to the current module. + val argumentFile = project.layout.buildDirectory.file("ktfmt-$name-args.txt").get().asFile + val lastRunTimeFile = + project.layout.buildDirectory.file("ktfmt-$name-last-run.txt").get().asFile + + // Read the time when this task was last executed for this module (if ever). + val lastRunTime = lastRunTimeFile.takeIf { it.exists() }?.readText()?.toLongOrNull() ?: 0L + + // Use a `fileTree` relative to the module's source directory. + val kotlinFiles = project.fileTree("src") { include("**/*.kt") } + + // Determine if any files need to be formatted or linted and continue only if there is at least + // one file (otherwise Ktfmt will fail). + onlyIf { kotlinFiles.any { it.lastModified() > lastRunTime } } + + inputs.files(kotlinFiles) + + doFirst { + // Create the argument file and set the preferred formatting style. + argumentFile.parentFile.mkdirs() + argumentFile.writeText("--kotlinlang-style\n") + + if (name == "lint") { + // For lint, do a dry run, so no files are modified. Set the exit code to 1 (instead of + // the default 0) if any files need to be formatted, indicating that linting has failed. + argumentFile.appendText("--dry-run\n") + argumentFile.appendText("--set-exit-if-changed\n") + } + + // Write the modified files to the argument file. + kotlinFiles.filter { it.lastModified() > lastRunTime } + .forEach { argumentFile.appendText("${it.absolutePath}\n") } + } + + doLast { + // Record the last execution time for later up-to-date checking. + lastRunTimeFile.writeText(System.currentTimeMillis().toString()) + } + + // Pass the argument file using the @ symbol + args = listOf("@${argumentFile.absolutePath}") + + outputs.upToDateWhen { kotlinFiles.none { it.lastModified() > lastRunTime } } + } + + tasks.named(name) { + dependsOn(tasks.named(kotlinName)) + } } + +registerKtfmt(name = "format", description = "Formats all Kotlin source files.") +registerKtfmt(name = "lint", description = "Verifies all Kotlin source files are formatted.") diff --git a/buildSrc/src/main/kotlin/hanzo.publish.gradle.kts b/buildSrc/src/main/kotlin/hanzo.publish.gradle.kts index 9e539251..2e3484a9 100644 --- a/buildSrc/src/main/kotlin/hanzo.publish.gradle.kts +++ b/buildSrc/src/main/kotlin/hanzo.publish.gradle.kts @@ -7,6 +7,17 @@ plugins { id("com.vanniktech.maven.publish") } +publishing { + repositories { + if (project.hasProperty("publishLocal")) { + maven { + name = "LocalFileSystem" + url = uri("${rootProject.layout.buildDirectory.get()}/local-maven-repo") + } + } + } +} + repositories { gradlePluginPortal() mavenCentral() @@ -17,8 +28,10 @@ extra["signingInMemoryKeyId"] = System.getenv("GPG_SIGNING_KEY_ID") extra["signingInMemoryKeyPassword"] = System.getenv("GPG_SIGNING_PASSWORD") configure { - signAllPublications() - publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL) + if (!project.hasProperty("publishLocal")) { + signAllPublications() + publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL) + } coordinates(project.group.toString(), project.name, project.version.toString()) configure( @@ -29,8 +42,8 @@ configure { ) pom { - name.set("Hanzo API") - description.set("Call 100+ LLMs in the OpenAI format. [**Docs**](https://docs.hanzo.ai/)\n\nšŸ‘‰ [`Hanzo Console`](https://cloud.hanzo.ai). Create, Edit API Keys.\n\nšŸ’ø [`LLM Models`](https://models.hanzo.ai/).") + name.set("LiteLLM API") + description.set("Proxy Server to call 100+ LLMs in the OpenAI format.\n[**Customize Swagger Docs**](https://docs.litellm.ai/docs/proxy/enterprise#swagger-docs---custom-routes--branding)\n\nšŸ‘‰ [`LiteLLM Admin Panel on /ui`](/ui). Create, Edit Keys with SSO. Having\nissues? Try [`Fallback Login`](/fallback/login)\n\nšŸ’ø [`LiteLLM Model Cost Map`](https://models.litellm.ai/).\n\nšŸ”Ž [`LiteLLM Model Hub`](/ui/model_hub_table). See available models on the\nproxy. [**Docs**](https://docs.litellm.ai/docs/proxy/ai_hub)") url.set("https://docs.hanzo.ai") licenses { @@ -53,3 +66,7 @@ configure { } } } + +tasks.withType().configureEach { + isZip64 = true +} diff --git a/gradle.properties b/gradle.properties index 0c8d4ded..6680f9ce 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,18 @@ org.gradle.caching=true +org.gradle.configuration-cache=true org.gradle.parallel=true org.gradle.daemon=false -org.gradle.jvmargs=-Xmx4g -kotlin.daemon.jvmargs=-Xmx4g +# These options improve our compilation and test performance. They are inherited by the Kotlin daemon. +org.gradle.jvmargs=\ + -Xms2g \ + -Xmx8g \ + -XX:+UseParallelGC \ + -XX:InitialCodeCacheSize=256m \ + -XX:ReservedCodeCacheSize=1G \ + -XX:MetaspaceSize=512m \ + -XX:MaxMetaspaceSize=2G \ + -XX:TieredStopAtLevel=1 \ + -XX:GCTimeRatio=4 \ + -XX:CICompilerCount=4 \ + -XX:+OptimizeStringConcat \ + -XX:+UseStringDeduplication diff --git a/hanzo-java-client-okhttp/build.gradle.kts b/hanzo-java-client-okhttp/build.gradle.kts index 20cd525a..4307d79f 100644 --- a/hanzo-java-client-okhttp/build.gradle.kts +++ b/hanzo-java-client-okhttp/build.gradle.kts @@ -11,4 +11,5 @@ dependencies { testImplementation(kotlin("test")) testImplementation("org.assertj:assertj-core:3.25.3") + testImplementation("com.github.tomakehurst:wiremock-jre8:2.35.2") } diff --git a/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClient.kt b/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClient.kt index 1965d611..139f16c1 100644 --- a/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClient.kt +++ b/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClient.kt @@ -5,21 +5,39 @@ package ai.hanzo.api.client.okhttp import ai.hanzo.api.client.HanzoClient import ai.hanzo.api.client.HanzoClientImpl import ai.hanzo.api.core.ClientOptions +import ai.hanzo.api.core.Sleeper import ai.hanzo.api.core.Timeout import ai.hanzo.api.core.http.Headers +import ai.hanzo.api.core.http.HttpClient import ai.hanzo.api.core.http.QueryParams +import ai.hanzo.api.core.jsonMapper import com.fasterxml.jackson.databind.json.JsonMapper import java.net.Proxy import java.time.Clock import java.time.Duration - +import java.util.Optional +import java.util.concurrent.ExecutorService +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509TrustManager +import kotlin.jvm.optionals.getOrNull + +/** + * A class that allows building an instance of [HanzoClient] with [OkHttpClient] as the underlying + * [HttpClient]. + */ class HanzoOkHttpClient private constructor() { companion object { - /** Returns a mutable builder for constructing an instance of [HanzoOkHttpClient]. */ + /** Returns a mutable builder for constructing an instance of [HanzoClient]. */ @JvmStatic fun builder() = Builder() + /** + * Returns a client configured using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ @JvmStatic fun fromEnv(): HanzoClient = builder().fromEnv().build() } @@ -27,17 +45,84 @@ class HanzoOkHttpClient private constructor() { class Builder internal constructor() { private var clientOptions: ClientOptions.Builder = ClientOptions.builder() - private var baseUrl: String = ClientOptions.PRODUCTION_URL - private var timeout: Timeout = Timeout.default() + private var dispatcherExecutorService: ExecutorService? = null private var proxy: Proxy? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null + + /** + * The executor service to use for running HTTP requests. + * + * Defaults to OkHttp's + * [default executor service](https://github.com/square/okhttp/blob/ace792f443b2ffb17974f5c0d1cecdf589309f26/okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt#L98-L104). + * + * This class takes ownership of the executor service and shuts it down when closed. + */ + fun dispatcherExecutorService(dispatcherExecutorService: ExecutorService?) = apply { + this.dispatcherExecutorService = dispatcherExecutorService + } + + /** + * Alias for calling [Builder.dispatcherExecutorService] with + * `dispatcherExecutorService.orElse(null)`. + */ + fun dispatcherExecutorService(dispatcherExecutorService: Optional) = + dispatcherExecutorService(dispatcherExecutorService.getOrNull()) + + fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } + + /** Alias for calling [Builder.proxy] with `proxy.orElse(null)`. */ + fun proxy(proxy: Optional) = proxy(proxy.getOrNull()) + + /** + * The socket factory used to secure HTTPS connections. + * + * If this is set, then [trustManager] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { + this.sslSocketFactory = sslSocketFactory + } + + /** Alias for calling [Builder.sslSocketFactory] with `sslSocketFactory.orElse(null)`. */ + fun sslSocketFactory(sslSocketFactory: Optional) = + sslSocketFactory(sslSocketFactory.getOrNull()) + + /** + * The trust manager used to secure HTTPS connections. + * + * If this is set, then [sslSocketFactory] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun trustManager(trustManager: X509TrustManager?) = apply { + this.trustManager = trustManager + } - fun sandbox() = apply { baseUrl(ClientOptions.SANDBOX_URL) } + /** Alias for calling [Builder.trustManager] with `trustManager.orElse(null)`. */ + fun trustManager(trustManager: Optional) = + trustManager(trustManager.getOrNull()) - fun baseUrl(baseUrl: String) = apply { - clientOptions.baseUrl(baseUrl) - this.baseUrl = baseUrl + /** + * The verifier used to confirm that response certificates apply to requested hostnames for + * HTTPS connections. + * + * If unset, then a default hostname verifier is used. + */ + fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { + this.hostnameVerifier = hostnameVerifier } + /** Alias for calling [Builder.hostnameVerifier] with `hostnameVerifier.orElse(null)`. */ + fun hostnameVerifier(hostnameVerifier: Optional) = + hostnameVerifier(hostnameVerifier.getOrNull()) + /** * Whether to throw an exception if any of the Jackson versions detected at runtime are * incompatible with the SDK's minimum supported Jackson version (2.13.4). @@ -49,10 +134,97 @@ class HanzoOkHttpClient private constructor() { clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) } + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [ai.hanzo.api.core.jsonMapper]. The default is usually sufficient and rarely + * needs to be overridden. + */ fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + fun sleeper(sleeper: Sleeper) = apply { clientOptions.sleeper(sleeper) } + + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ fun clock(clock: Clock) = apply { clientOptions.clock(clock) } + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.hanzo.ai`. + * + * The following other environments, with dedicated builder methods, are available: + * - sandbox: `https://api.sandbox.hanzo.ai` + */ + fun baseUrl(baseUrl: String?) = apply { clientOptions.baseUrl(baseUrl) } + + /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ + fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) + + /** Sets [baseUrl] to `https://api.sandbox.hanzo.ai`. */ + fun sandbox() = apply { clientOptions.sandbox() } + + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ + fun responseValidation(responseValidation: Boolean) = apply { + clientOptions.responseValidation(responseValidation) + } + + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ + fun timeout(timeout: Timeout) = apply { clientOptions.timeout(timeout) } + + /** + * Sets the maximum time allowed for a complete HTTP call, not including retries. + * + * See [Timeout.request] for more details. + * + * For fine-grained control, pass a [Timeout] object. + */ + fun timeout(timeout: Duration) = apply { clientOptions.timeout(timeout) } + + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ + fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } + + /** The default name of the subscription key header of Azure */ + fun apiKey(apiKey: String) = apply { clientOptions.apiKey(apiKey) } + fun headers(headers: Headers) = apply { clientOptions.headers(headers) } fun headers(headers: Map>) = apply { @@ -133,30 +305,11 @@ class HanzoOkHttpClient private constructor() { clientOptions.removeAllQueryParams(keys) } - fun timeout(timeout: Timeout) = apply { - clientOptions.timeout(timeout) - this.timeout = timeout - } - /** - * Sets the maximum time allowed for a complete HTTP call, not including retries. - * - * See [Timeout.request] for more details. + * Updates configuration using system properties and environment variables. * - * For fine-grained control, pass a [Timeout] object. + * @see ClientOptions.Builder.fromEnv */ - fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) - - fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } - - fun proxy(proxy: Proxy) = apply { this.proxy = proxy } - - fun responseValidation(responseValidation: Boolean) = apply { - clientOptions.responseValidation(responseValidation) - } - - fun apiKey(apiKey: String) = apply { clientOptions.apiKey(apiKey) } - fun fromEnv() = apply { clientOptions.fromEnv() } /** @@ -169,9 +322,12 @@ class HanzoOkHttpClient private constructor() { clientOptions .httpClient( OkHttpClient.builder() - .baseUrl(baseUrl) - .timeout(timeout) + .timeout(clientOptions.timeout()) .proxy(proxy) + .dispatcherExecutorService(dispatcherExecutorService) + .sslSocketFactory(sslSocketFactory) + .trustManager(trustManager) + .hostnameVerifier(hostnameVerifier) .build() ) .build() diff --git a/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClientAsync.kt b/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClientAsync.kt index 68a77b16..d6689bbc 100644 --- a/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClientAsync.kt +++ b/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/HanzoOkHttpClientAsync.kt @@ -5,21 +5,39 @@ package ai.hanzo.api.client.okhttp import ai.hanzo.api.client.HanzoClientAsync import ai.hanzo.api.client.HanzoClientAsyncImpl import ai.hanzo.api.core.ClientOptions +import ai.hanzo.api.core.Sleeper import ai.hanzo.api.core.Timeout import ai.hanzo.api.core.http.Headers +import ai.hanzo.api.core.http.HttpClient import ai.hanzo.api.core.http.QueryParams +import ai.hanzo.api.core.jsonMapper import com.fasterxml.jackson.databind.json.JsonMapper import java.net.Proxy import java.time.Clock import java.time.Duration - +import java.util.Optional +import java.util.concurrent.ExecutorService +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509TrustManager +import kotlin.jvm.optionals.getOrNull + +/** + * A class that allows building an instance of [HanzoClientAsync] with [OkHttpClient] as the + * underlying [HttpClient]. + */ class HanzoOkHttpClientAsync private constructor() { companion object { - /** Returns a mutable builder for constructing an instance of [HanzoOkHttpClientAsync]. */ + /** Returns a mutable builder for constructing an instance of [HanzoClientAsync]. */ @JvmStatic fun builder() = Builder() + /** + * Returns a client configured using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ @JvmStatic fun fromEnv(): HanzoClientAsync = builder().fromEnv().build() } @@ -27,17 +45,84 @@ class HanzoOkHttpClientAsync private constructor() { class Builder internal constructor() { private var clientOptions: ClientOptions.Builder = ClientOptions.builder() - private var baseUrl: String = ClientOptions.PRODUCTION_URL - private var timeout: Timeout = Timeout.default() + private var dispatcherExecutorService: ExecutorService? = null private var proxy: Proxy? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null + + /** + * The executor service to use for running HTTP requests. + * + * Defaults to OkHttp's + * [default executor service](https://github.com/square/okhttp/blob/ace792f443b2ffb17974f5c0d1cecdf589309f26/okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt#L98-L104). + * + * This class takes ownership of the executor service and shuts it down when closed. + */ + fun dispatcherExecutorService(dispatcherExecutorService: ExecutorService?) = apply { + this.dispatcherExecutorService = dispatcherExecutorService + } + + /** + * Alias for calling [Builder.dispatcherExecutorService] with + * `dispatcherExecutorService.orElse(null)`. + */ + fun dispatcherExecutorService(dispatcherExecutorService: Optional) = + dispatcherExecutorService(dispatcherExecutorService.getOrNull()) + + fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } + + /** Alias for calling [Builder.proxy] with `proxy.orElse(null)`. */ + fun proxy(proxy: Optional) = proxy(proxy.getOrNull()) + + /** + * The socket factory used to secure HTTPS connections. + * + * If this is set, then [trustManager] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { + this.sslSocketFactory = sslSocketFactory + } + + /** Alias for calling [Builder.sslSocketFactory] with `sslSocketFactory.orElse(null)`. */ + fun sslSocketFactory(sslSocketFactory: Optional) = + sslSocketFactory(sslSocketFactory.getOrNull()) + + /** + * The trust manager used to secure HTTPS connections. + * + * If this is set, then [sslSocketFactory] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun trustManager(trustManager: X509TrustManager?) = apply { + this.trustManager = trustManager + } - fun sandbox() = apply { baseUrl(ClientOptions.SANDBOX_URL) } + /** Alias for calling [Builder.trustManager] with `trustManager.orElse(null)`. */ + fun trustManager(trustManager: Optional) = + trustManager(trustManager.getOrNull()) - fun baseUrl(baseUrl: String) = apply { - clientOptions.baseUrl(baseUrl) - this.baseUrl = baseUrl + /** + * The verifier used to confirm that response certificates apply to requested hostnames for + * HTTPS connections. + * + * If unset, then a default hostname verifier is used. + */ + fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { + this.hostnameVerifier = hostnameVerifier } + /** Alias for calling [Builder.hostnameVerifier] with `hostnameVerifier.orElse(null)`. */ + fun hostnameVerifier(hostnameVerifier: Optional) = + hostnameVerifier(hostnameVerifier.getOrNull()) + /** * Whether to throw an exception if any of the Jackson versions detected at runtime are * incompatible with the SDK's minimum supported Jackson version (2.13.4). @@ -49,10 +134,97 @@ class HanzoOkHttpClientAsync private constructor() { clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) } + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [ai.hanzo.api.core.jsonMapper]. The default is usually sufficient and rarely + * needs to be overridden. + */ fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + fun sleeper(sleeper: Sleeper) = apply { clientOptions.sleeper(sleeper) } + + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ fun clock(clock: Clock) = apply { clientOptions.clock(clock) } + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.hanzo.ai`. + * + * The following other environments, with dedicated builder methods, are available: + * - sandbox: `https://api.sandbox.hanzo.ai` + */ + fun baseUrl(baseUrl: String?) = apply { clientOptions.baseUrl(baseUrl) } + + /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ + fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) + + /** Sets [baseUrl] to `https://api.sandbox.hanzo.ai`. */ + fun sandbox() = apply { clientOptions.sandbox() } + + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ + fun responseValidation(responseValidation: Boolean) = apply { + clientOptions.responseValidation(responseValidation) + } + + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ + fun timeout(timeout: Timeout) = apply { clientOptions.timeout(timeout) } + + /** + * Sets the maximum time allowed for a complete HTTP call, not including retries. + * + * See [Timeout.request] for more details. + * + * For fine-grained control, pass a [Timeout] object. + */ + fun timeout(timeout: Duration) = apply { clientOptions.timeout(timeout) } + + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ + fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } + + /** The default name of the subscription key header of Azure */ + fun apiKey(apiKey: String) = apply { clientOptions.apiKey(apiKey) } + fun headers(headers: Headers) = apply { clientOptions.headers(headers) } fun headers(headers: Map>) = apply { @@ -133,30 +305,11 @@ class HanzoOkHttpClientAsync private constructor() { clientOptions.removeAllQueryParams(keys) } - fun timeout(timeout: Timeout) = apply { - clientOptions.timeout(timeout) - this.timeout = timeout - } - /** - * Sets the maximum time allowed for a complete HTTP call, not including retries. - * - * See [Timeout.request] for more details. + * Updates configuration using system properties and environment variables. * - * For fine-grained control, pass a [Timeout] object. + * @see ClientOptions.Builder.fromEnv */ - fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) - - fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } - - fun proxy(proxy: Proxy) = apply { this.proxy = proxy } - - fun responseValidation(responseValidation: Boolean) = apply { - clientOptions.responseValidation(responseValidation) - } - - fun apiKey(apiKey: String) = apply { clientOptions.apiKey(apiKey) } - fun fromEnv() = apply { clientOptions.fromEnv() } /** @@ -169,9 +322,12 @@ class HanzoOkHttpClientAsync private constructor() { clientOptions .httpClient( OkHttpClient.builder() - .baseUrl(baseUrl) - .timeout(timeout) + .timeout(clientOptions.timeout()) .proxy(proxy) + .dispatcherExecutorService(dispatcherExecutorService) + .sslSocketFactory(sslSocketFactory) + .trustManager(trustManager) + .hostnameVerifier(hostnameVerifier) .build() ) .build() diff --git a/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/OkHttpClient.kt b/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/OkHttpClient.kt index 3b93ec84..3dc8e1a6 100644 --- a/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/OkHttpClient.kt +++ b/hanzo-java-client-okhttp/src/main/kotlin/ai/hanzo/api/client/okhttp/OkHttpClient.kt @@ -2,7 +2,6 @@ package ai.hanzo.api.client.okhttp import ai.hanzo.api.core.RequestOptions import ai.hanzo.api.core.Timeout -import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.http.Headers import ai.hanzo.api.core.http.HttpClient import ai.hanzo.api.core.http.HttpMethod @@ -14,10 +13,15 @@ import java.io.IOException import java.io.InputStream import java.net.Proxy import java.time.Duration +import java.util.concurrent.CancellationException import java.util.concurrent.CompletableFuture +import java.util.concurrent.ExecutorService +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509TrustManager import okhttp3.Call import okhttp3.Callback -import okhttp3.HttpUrl +import okhttp3.Dispatcher import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType import okhttp3.MediaType.Companion.toMediaType @@ -29,8 +33,7 @@ import okhttp3.logging.HttpLoggingInterceptor import okio.BufferedSink class OkHttpClient -private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val baseUrl: HttpUrl) : - HttpClient { +private constructor(@JvmSynthetic internal val okHttpClient: okhttp3.OkHttpClient) : HttpClient { override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse { val call = newCall(request, requestOptions) @@ -50,20 +53,25 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val ): CompletableFuture { val future = CompletableFuture() - request.body?.run { future.whenComplete { _, _ -> close() } } - - newCall(request, requestOptions) - .enqueue( - object : Callback { - override fun onResponse(call: Call, response: Response) { - future.complete(response.toResponse()) - } + val call = newCall(request, requestOptions) + call.enqueue( + object : Callback { + override fun onResponse(call: Call, response: Response) { + future.complete(response.toResponse()) + } - override fun onFailure(call: Call, e: IOException) { - future.completeExceptionally(HanzoIoException("Request failed", e)) - } + override fun onFailure(call: Call, e: IOException) { + future.completeExceptionally(HanzoIoException("Request failed", e)) } - ) + } + ) + + future.whenComplete { _, e -> + if (e is CancellationException) { + call.cancel() + } + request.body?.close() + } return future } @@ -86,7 +94,7 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val if (logLevel != null) { clientBuilder.addNetworkInterceptor( HttpLoggingInterceptor().setLevel(logLevel).apply { - redactHeader("Ocp-Apim-Subscription-Key") + redactHeader("x-litellm-api-key") } ) } @@ -111,19 +119,19 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val val builder = Request.Builder().url(toUrl()).method(method.name, body) headers.names().forEach { name -> - headers.values(name).forEach { builder.header(name, it) } + headers.values(name).forEach { builder.addHeader(name, it) } } if ( !headers.names().contains("X-Stainless-Read-Timeout") && client.readTimeoutMillis != 0 ) { - builder.header( + builder.addHeader( "X-Stainless-Read-Timeout", Duration.ofMillis(client.readTimeoutMillis.toLong()).seconds.toString(), ) } if (!headers.names().contains("X-Stainless-Timeout") && client.callTimeoutMillis != 0) { - builder.header( + builder.addHeader( "X-Stainless-Timeout", Duration.ofMillis(client.callTimeoutMillis.toLong()).seconds.toString(), ) @@ -142,11 +150,7 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val } private fun HttpRequest.toUrl(): String { - url?.let { - return it - } - - val builder = baseUrl.newBuilder() + val builder = baseUrl.toHttpUrl().newBuilder() pathSegments.forEach(builder::addPathSegment) queryParams.keys().forEach { key -> queryParams.values(key).forEach { builder.addQueryParameter(key, it) } @@ -196,11 +200,12 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val class Builder internal constructor() { - private var baseUrl: HttpUrl? = null private var timeout: Timeout = Timeout.default() private var proxy: Proxy? = null - - fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl.toHttpUrl() } + private var dispatcherExecutorService: ExecutorService? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null fun timeout(timeout: Timeout) = apply { this.timeout = timeout } @@ -208,16 +213,53 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } + fun dispatcherExecutorService(dispatcherExecutorService: ExecutorService?) = apply { + this.dispatcherExecutorService = dispatcherExecutorService + } + + fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { + this.sslSocketFactory = sslSocketFactory + } + + fun trustManager(trustManager: X509TrustManager?) = apply { + this.trustManager = trustManager + } + + fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { + this.hostnameVerifier = hostnameVerifier + } + fun build(): OkHttpClient = OkHttpClient( okhttp3.OkHttpClient.Builder() + // `RetryingHttpClient` handles retries if the user enabled them. + .retryOnConnectionFailure(false) .connectTimeout(timeout.connect()) .readTimeout(timeout.read()) .writeTimeout(timeout.write()) .callTimeout(timeout.request()) .proxy(proxy) - .build(), - checkRequired("baseUrl", baseUrl), + .apply { + dispatcherExecutorService?.let { dispatcher(Dispatcher(it)) } + + val sslSocketFactory = sslSocketFactory + val trustManager = trustManager + if (sslSocketFactory != null && trustManager != null) { + sslSocketFactory(sslSocketFactory, trustManager) + } else { + check((sslSocketFactory != null) == (trustManager != null)) { + "Both or none of `sslSocketFactory` and `trustManager` must be set, but only one was set" + } + } + + hostnameVerifier?.let(::hostnameVerifier) + } + .build() + .apply { + // We usually make all our requests to the same host so it makes sense to + // raise the per-host limit to the overall limit. + dispatcher.maxRequestsPerHost = dispatcher.maxRequests + } ) } } diff --git a/hanzo-java-client-okhttp/src/test/kotlin/ai/hanzo/api/client/okhttp/OkHttpClientTest.kt b/hanzo-java-client-okhttp/src/test/kotlin/ai/hanzo/api/client/okhttp/OkHttpClientTest.kt new file mode 100644 index 00000000..7f855e39 --- /dev/null +++ b/hanzo-java-client-okhttp/src/test/kotlin/ai/hanzo/api/client/okhttp/OkHttpClientTest.kt @@ -0,0 +1,44 @@ +package ai.hanzo.api.client.okhttp + +import ai.hanzo.api.core.http.HttpMethod +import ai.hanzo.api.core.http.HttpRequest +import com.github.tomakehurst.wiremock.client.WireMock.* +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo +import com.github.tomakehurst.wiremock.junit5.WireMockTest +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.parallel.ResourceLock + +@WireMockTest +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") +internal class OkHttpClientTest { + + private lateinit var baseUrl: String + private lateinit var httpClient: OkHttpClient + + @BeforeEach + fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { + baseUrl = wmRuntimeInfo.httpBaseUrl + httpClient = OkHttpClient.builder().build() + } + + @Test + fun executeAsync_whenFutureCancelled_cancelsUnderlyingCall() { + stubFor(post(urlPathEqualTo("/something")).willReturn(ok())) + val responseFuture = + httpClient.executeAsync( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build() + ) + val call = httpClient.okHttpClient.dispatcher.runningCalls().single() + + responseFuture.cancel(false) + + // Should have cancelled the underlying call + assertThat(call.isCanceled()).isTrue() + } +} diff --git a/hanzo-java-core/build.gradle.kts b/hanzo-java-core/build.gradle.kts index 18a11075..4d1c6331 100644 --- a/hanzo-java-core/build.gradle.kts +++ b/hanzo-java-core/build.gradle.kts @@ -5,26 +5,28 @@ plugins { configurations.all { resolutionStrategy { - // Compile and test against a lower Jackson version to ensure we're compatible with it. - // We publish with a higher version (see below) to ensure users depend on a secure version by default. - force("com.fasterxml.jackson.core:jackson-core:2.13.4") - force("com.fasterxml.jackson.core:jackson-databind:2.13.4") - force("com.fasterxml.jackson.core:jackson-annotations:2.13.4") - force("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.13.4") - force("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.4") - force("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.4") + // Compile and test against a lower Jackson version to ensure we're compatible with it. Note that + // we generally support 2.13.4, but test against 2.14.0 because 2.13.4 has some annoying (but + // niche) bugs (users should upgrade if they encounter them). We publish with a higher version + // (see below) to ensure users depend on a secure version by default. + force("com.fasterxml.jackson.core:jackson-core:2.14.0") + force("com.fasterxml.jackson.core:jackson-databind:2.14.0") + force("com.fasterxml.jackson.core:jackson-annotations:2.14.0") + force("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.14.0") + force("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.0") + force("com.fasterxml.jackson.module:jackson-module-kotlin:2.14.0") } } dependencies { - api("com.fasterxml.jackson.core:jackson-core:2.18.1") - api("com.fasterxml.jackson.core:jackson-databind:2.18.1") + api("com.fasterxml.jackson.core:jackson-core:2.18.2") + api("com.fasterxml.jackson.core:jackson-databind:2.18.2") api("com.google.errorprone:error_prone_annotations:2.33.0") - implementation("com.fasterxml.jackson.core:jackson-annotations:2.18.1") - implementation("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.18.1") - implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.18.1") - implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.18.1") + implementation("com.fasterxml.jackson.core:jackson-annotations:2.18.2") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.18.2") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.18.2") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.18.2") implementation("org.apache.httpcomponents.core5:httpcore5:5.2.4") implementation("org.apache.httpcomponents.client5:httpclient5:5.3.1") @@ -34,6 +36,7 @@ dependencies { testImplementation("org.assertj:assertj-core:3.25.3") testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.3") testImplementation("org.junit.jupiter:junit-jupiter-params:5.9.3") + testImplementation("org.junit-pioneer:junit-pioneer:1.9.1") testImplementation("org.mockito:mockito-core:5.14.2") testImplementation("org.mockito:mockito-junit-jupiter:5.14.2") testImplementation("org.mockito.kotlin:mockito-kotlin:4.1.0") diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClient.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClient.kt index 5ba61eca..8400c4d5 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClient.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClient.kt @@ -2,6 +2,7 @@ package ai.hanzo.api.client +import ai.hanzo.api.core.ClientOptions import ai.hanzo.api.core.RequestOptions import ai.hanzo.api.core.http.HttpResponseFor import ai.hanzo.api.models.ClientGetHomeParams @@ -54,6 +55,7 @@ import ai.hanzo.api.services.blocking.UserService import ai.hanzo.api.services.blocking.UtilService import ai.hanzo.api.services.blocking.VertexAiService import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer /** * A client for interacting with the Hanzo REST API synchronously. You can also switch to @@ -84,6 +86,13 @@ interface HanzoClient { */ fun withRawResponse(): WithRawResponse + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): HanzoClient + fun models(): ModelService fun openai(): OpenAIService @@ -183,17 +192,17 @@ interface HanzoClient { /** Home */ fun getHome(): ClientGetHomeResponse = getHome(ClientGetHomeParams.none()) - /** @see [getHome] */ + /** @see getHome */ fun getHome( params: ClientGetHomeParams = ClientGetHomeParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): ClientGetHomeResponse - /** @see [getHome] */ + /** @see getHome */ fun getHome(params: ClientGetHomeParams = ClientGetHomeParams.none()): ClientGetHomeResponse = getHome(params, RequestOptions.none()) - /** @see [getHome] */ + /** @see getHome */ fun getHome(requestOptions: RequestOptions): ClientGetHomeResponse = getHome(ClientGetHomeParams.none(), requestOptions) @@ -213,6 +222,13 @@ interface HanzoClient { /** A view of [HanzoClient] that provides access to raw HTTP responses for each method. */ interface WithRawResponse { + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): HanzoClient.WithRawResponse + fun models(): ModelService.WithRawResponse fun openai(): OpenAIService.WithRawResponse @@ -316,20 +332,20 @@ interface HanzoClient { @MustBeClosed fun getHome(): HttpResponseFor = getHome(ClientGetHomeParams.none()) - /** @see [getHome] */ + /** @see getHome */ @MustBeClosed fun getHome( params: ClientGetHomeParams = ClientGetHomeParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): HttpResponseFor - /** @see [getHome] */ + /** @see getHome */ @MustBeClosed fun getHome( params: ClientGetHomeParams = ClientGetHomeParams.none() ): HttpResponseFor = getHome(params, RequestOptions.none()) - /** @see [getHome] */ + /** @see getHome */ @MustBeClosed fun getHome(requestOptions: RequestOptions): HttpResponseFor = getHome(ClientGetHomeParams.none(), requestOptions) diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsync.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsync.kt index e9905a45..7b73152f 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsync.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsync.kt @@ -2,6 +2,7 @@ package ai.hanzo.api.client +import ai.hanzo.api.core.ClientOptions import ai.hanzo.api.core.RequestOptions import ai.hanzo.api.core.http.HttpResponseFor import ai.hanzo.api.models.ClientGetHomeParams @@ -53,8 +54,8 @@ import ai.hanzo.api.services.async.ThreadServiceAsync import ai.hanzo.api.services.async.UserServiceAsync import ai.hanzo.api.services.async.UtilServiceAsync import ai.hanzo.api.services.async.VertexAiServiceAsync -import com.google.errorprone.annotations.MustBeClosed import java.util.concurrent.CompletableFuture +import java.util.function.Consumer /** * A client for interacting with the Hanzo REST API asynchronously. You can also switch to @@ -85,6 +86,13 @@ interface HanzoClientAsync { */ fun withRawResponse(): WithRawResponse + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): HanzoClientAsync + fun models(): ModelServiceAsync fun openai(): OpenAIServiceAsync @@ -184,18 +192,18 @@ interface HanzoClientAsync { /** Home */ fun getHome(): CompletableFuture = getHome(ClientGetHomeParams.none()) - /** @see [getHome] */ + /** @see getHome */ fun getHome( params: ClientGetHomeParams = ClientGetHomeParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** @see [getHome] */ + /** @see getHome */ fun getHome( params: ClientGetHomeParams = ClientGetHomeParams.none() ): CompletableFuture = getHome(params, RequestOptions.none()) - /** @see [getHome] */ + /** @see getHome */ fun getHome(requestOptions: RequestOptions): CompletableFuture = getHome(ClientGetHomeParams.none(), requestOptions) @@ -215,6 +223,13 @@ interface HanzoClientAsync { /** A view of [HanzoClientAsync] that provides access to raw HTTP responses for each method. */ interface WithRawResponse { + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): HanzoClientAsync.WithRawResponse + fun models(): ModelServiceAsync.WithRawResponse fun openai(): OpenAIServiceAsync.WithRawResponse @@ -315,26 +330,22 @@ interface HanzoClientAsync { * Returns a raw HTTP response for `get /`, but is otherwise the same as * [HanzoClientAsync.getHome]. */ - @MustBeClosed fun getHome(): CompletableFuture> = getHome(ClientGetHomeParams.none()) - /** @see [getHome] */ - @MustBeClosed + /** @see getHome */ fun getHome( params: ClientGetHomeParams = ClientGetHomeParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture> - /** @see [getHome] */ - @MustBeClosed + /** @see getHome */ fun getHome( params: ClientGetHomeParams = ClientGetHomeParams.none() ): CompletableFuture> = getHome(params, RequestOptions.none()) - /** @see [getHome] */ - @MustBeClosed + /** @see getHome */ fun getHome( requestOptions: RequestOptions ): CompletableFuture> = diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsyncImpl.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsyncImpl.kt index 81849c7f..1441a129 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsyncImpl.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientAsyncImpl.kt @@ -3,14 +3,14 @@ package ai.hanzo.api.client import ai.hanzo.api.core.ClientOptions -import ai.hanzo.api.core.JsonValue import ai.hanzo.api.core.RequestOptions import ai.hanzo.api.core.getPackageVersion +import ai.hanzo.api.core.handlers.errorBodyHandler import ai.hanzo.api.core.handlers.errorHandler import ai.hanzo.api.core.handlers.jsonHandler -import ai.hanzo.api.core.handlers.withErrorHandler import ai.hanzo.api.core.http.HttpMethod import ai.hanzo.api.core.http.HttpRequest +import ai.hanzo.api.core.http.HttpResponse import ai.hanzo.api.core.http.HttpResponse.Handler import ai.hanzo.api.core.http.HttpResponseFor import ai.hanzo.api.core.http.parseable @@ -112,6 +112,7 @@ import ai.hanzo.api.services.async.UtilServiceAsyncImpl import ai.hanzo.api.services.async.VertexAiServiceAsync import ai.hanzo.api.services.async.VertexAiServiceAsyncImpl import java.util.concurrent.CompletableFuture +import java.util.function.Consumer class HanzoClientAsyncImpl(private val clientOptions: ClientOptions) : HanzoClientAsync { @@ -310,6 +311,9 @@ class HanzoClientAsyncImpl(private val clientOptions: ClientOptions) : HanzoClie override fun withRawResponse(): HanzoClientAsync.WithRawResponse = withRawResponse + override fun withOptions(modifier: Consumer): HanzoClientAsync = + HanzoClientAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun models(): ModelServiceAsync = models override fun openai(): OpenAIServiceAsync = openai @@ -413,12 +417,13 @@ class HanzoClientAsyncImpl(private val clientOptions: ClientOptions) : HanzoClie // get / withRawResponse().getHome(params, requestOptions).thenApply { it.parse() } - override fun close() = clientOptions.httpClient.close() + override fun close() = clientOptions.close() class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : HanzoClientAsync.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) private val models: ModelServiceAsync.WithRawResponse by lazy { ModelServiceAsyncImpl.WithRawResponseImpl(clientOptions) @@ -612,6 +617,13 @@ class HanzoClientAsyncImpl(private val clientOptions: ClientOptions) : HanzoClie BudgetServiceAsyncImpl.WithRawResponseImpl(clientOptions) } + override fun withOptions( + modifier: Consumer + ): HanzoClientAsync.WithRawResponse = + HanzoClientAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + override fun models(): ModelServiceAsync.WithRawResponse = models override fun openai(): OpenAIServiceAsync.WithRawResponse = openai @@ -710,7 +722,6 @@ class HanzoClientAsyncImpl(private val clientOptions: ClientOptions) : HanzoClie private val getHomeHandler: Handler = jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) override fun getHome( params: ClientGetHomeParams, @@ -719,6 +730,7 @@ class HanzoClientAsyncImpl(private val clientOptions: ClientOptions) : HanzoClie val request = HttpRequest.builder() .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) .addPathSegments("") .build() .prepareAsync(clientOptions, params) @@ -726,7 +738,7 @@ class HanzoClientAsyncImpl(private val clientOptions: ClientOptions) : HanzoClie return request .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } .thenApply { response -> - response.parseable { + errorHandler.handle(response).parseable { response .use { getHomeHandler.handle(it) } .also { diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientImpl.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientImpl.kt index 866f48ca..43e98b9f 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientImpl.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/client/HanzoClientImpl.kt @@ -3,14 +3,14 @@ package ai.hanzo.api.client import ai.hanzo.api.core.ClientOptions -import ai.hanzo.api.core.JsonValue import ai.hanzo.api.core.RequestOptions import ai.hanzo.api.core.getPackageVersion +import ai.hanzo.api.core.handlers.errorBodyHandler import ai.hanzo.api.core.handlers.errorHandler import ai.hanzo.api.core.handlers.jsonHandler -import ai.hanzo.api.core.handlers.withErrorHandler import ai.hanzo.api.core.http.HttpMethod import ai.hanzo.api.core.http.HttpRequest +import ai.hanzo.api.core.http.HttpResponse import ai.hanzo.api.core.http.HttpResponse.Handler import ai.hanzo.api.core.http.HttpResponseFor import ai.hanzo.api.core.http.parseable @@ -111,6 +111,7 @@ import ai.hanzo.api.services.blocking.UtilService import ai.hanzo.api.services.blocking.UtilServiceImpl import ai.hanzo.api.services.blocking.VertexAiService import ai.hanzo.api.services.blocking.VertexAiServiceImpl +import java.util.function.Consumer class HanzoClientImpl(private val clientOptions: ClientOptions) : HanzoClient { @@ -263,6 +264,9 @@ class HanzoClientImpl(private val clientOptions: ClientOptions) : HanzoClient { override fun withRawResponse(): HanzoClient.WithRawResponse = withRawResponse + override fun withOptions(modifier: Consumer): HanzoClient = + HanzoClientImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun models(): ModelService = models override fun openai(): OpenAIService = openai @@ -366,12 +370,13 @@ class HanzoClientImpl(private val clientOptions: ClientOptions) : HanzoClient { // get / withRawResponse().getHome(params, requestOptions).parse() - override fun close() = clientOptions.httpClient.close() + override fun close() = clientOptions.close() class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : HanzoClient.WithRawResponse { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) private val models: ModelService.WithRawResponse by lazy { ModelServiceImpl.WithRawResponseImpl(clientOptions) @@ -565,6 +570,13 @@ class HanzoClientImpl(private val clientOptions: ClientOptions) : HanzoClient { BudgetServiceImpl.WithRawResponseImpl(clientOptions) } + override fun withOptions( + modifier: Consumer + ): HanzoClient.WithRawResponse = + HanzoClientImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + override fun models(): ModelService.WithRawResponse = models override fun openai(): OpenAIService.WithRawResponse = openai @@ -663,7 +675,6 @@ class HanzoClientImpl(private val clientOptions: ClientOptions) : HanzoClient { private val getHomeHandler: Handler = jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) override fun getHome( params: ClientGetHomeParams, @@ -672,12 +683,13 @@ class HanzoClientImpl(private val clientOptions: ClientOptions) : HanzoClient { val request = HttpRequest.builder() .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) .addPathSegments("") .build() .prepare(clientOptions, params) val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) val response = clientOptions.httpClient.execute(request, requestOptions) - return response.parseable { + return errorHandler.handle(response).parseable { response .use { getHomeHandler.handle(it) } .also { diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/BaseDeserializer.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/BaseDeserializer.kt index 6d563247..e05d3136 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/BaseDeserializer.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/BaseDeserializer.kt @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.BeanProperty import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JavaType import com.fasterxml.jackson.databind.JsonDeserializer -import com.fasterxml.jackson.databind.JsonMappingException import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.deser.ContextualDeserializer import com.fasterxml.jackson.databind.deser.std.StdDeserializer @@ -29,31 +28,17 @@ abstract class BaseDeserializer(type: KClass) : protected abstract fun ObjectCodec.deserialize(node: JsonNode): T - protected fun ObjectCodec.tryDeserialize( - node: JsonNode, - type: TypeReference, - validate: (T) -> Unit = {}, - ): T? { - return try { - readValue(treeAsTokens(node), type).apply(validate) - } catch (e: JsonMappingException) { - null - } catch (e: RuntimeException) { + protected fun ObjectCodec.tryDeserialize(node: JsonNode, type: TypeReference): T? = + try { + readValue(treeAsTokens(node), type) + } catch (e: Exception) { null } - } - protected fun ObjectCodec.tryDeserialize( - node: JsonNode, - type: JavaType, - validate: (T) -> Unit = {}, - ): T? { - return try { - readValue(treeAsTokens(node), type).apply(validate) - } catch (e: JsonMappingException) { - null - } catch (e: RuntimeException) { + protected fun ObjectCodec.tryDeserialize(node: JsonNode, type: JavaType): T? = + try { + readValue(treeAsTokens(node), type) + } catch (e: Exception) { null } - } } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Check.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Check.kt index 48b8a942..56ae907e 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Check.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Check.kt @@ -5,6 +5,9 @@ package ai.hanzo.api.core import com.fasterxml.jackson.core.Version import com.fasterxml.jackson.core.util.VersionUtil +fun checkRequired(name: String, condition: Boolean) = + check(condition) { "`$name` is required, but was not set" } + fun checkRequired(name: String, value: T?): T = checkNotNull(value) { "`$name` is required, but was not set" } @@ -47,6 +50,7 @@ internal fun checkMaxLength(name: String, value: String, maxLength: Int): String internal fun checkJacksonVersionCompatibility() { val incompatibleJacksonVersions = RUNTIME_JACKSON_VERSIONS.mapNotNull { + val badVersionReason = BAD_JACKSON_VERSIONS[it.toString()] when { it.majorVersion != MINIMUM_JACKSON_VERSION.majorVersion -> it to "incompatible major version" @@ -55,12 +59,13 @@ internal fun checkJacksonVersionCompatibility() { it.minorVersion == MINIMUM_JACKSON_VERSION.minorVersion && it.patchLevel < MINIMUM_JACKSON_VERSION.patchLevel -> it to "patch version too low" + badVersionReason != null -> it to badVersionReason else -> null } } check(incompatibleJacksonVersions.isEmpty()) { """ -This SDK depends on Jackson version $MINIMUM_JACKSON_VERSION, but the following incompatible Jackson versions were detected at runtime: +This SDK requires a minimum Jackson version of $MINIMUM_JACKSON_VERSION, but the following incompatible Jackson versions were detected at runtime: ${incompatibleJacksonVersions.asSequence().map { (version, incompatibilityReason) -> "- `${version.toFullString().replace("/", ":")}` ($incompatibilityReason)" @@ -71,12 +76,16 @@ This can happen if you are either: 2. Depending on some library that depends on different Jackson versions, potentially transitively Double-check that you are depending on compatible Jackson versions. + +See https://www.github.com/hanzoai/java-sdk#jackson for more information. """ .trimIndent() } } private val MINIMUM_JACKSON_VERSION: Version = VersionUtil.parseVersion("2.13.4", null, null) +private val BAD_JACKSON_VERSIONS: Map = + mapOf("2.18.1" to "due to https://github.com/FasterXML/jackson-databind/issues/4639") private val RUNTIME_JACKSON_VERSIONS: List = listOf( com.fasterxml.jackson.core.json.PackageVersion.VERSION, diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/ClientOptions.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/ClientOptions.kt index e67044be..66631ea7 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/ClientOptions.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/ClientOptions.kt @@ -9,20 +9,91 @@ import ai.hanzo.api.core.http.QueryParams import ai.hanzo.api.core.http.RetryingHttpClient import com.fasterxml.jackson.databind.json.JsonMapper import java.time.Clock +import java.time.Duration +import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** A class representing the SDK client configuration. */ class ClientOptions private constructor( private val originalHttpClient: HttpClient, + /** + * The HTTP client to use in the SDK. + * + * Use the one published in `hanzo-java-client-okhttp` or implement your own. + * + * This class takes ownership of the client and closes it when closed. + */ @get:JvmName("httpClient") val httpClient: HttpClient, + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee that + * the SDK will work correctly when using an incompatible Jackson version. + */ @get:JvmName("checkJacksonVersionCompatibility") val checkJacksonVersionCompatibility: Boolean, + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [ai.hanzo.api.core.jsonMapper]. The default is usually sufficient and rarely + * needs to be overridden. + */ @get:JvmName("jsonMapper") val jsonMapper: JsonMapper, + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + @get:JvmName("sleeper") val sleeper: Sleeper, + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ @get:JvmName("clock") val clock: Clock, - @get:JvmName("baseUrl") val baseUrl: String, + private val baseUrl: String?, + /** Headers to send with the request. */ @get:JvmName("headers") val headers: Headers, + /** Query params to send with the request. */ @get:JvmName("queryParams") val queryParams: QueryParams, + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ @get:JvmName("responseValidation") val responseValidation: Boolean, + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ @get:JvmName("timeout") val timeout: Timeout, + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ @get:JvmName("maxRetries") val maxRetries: Int, + /** The default name of the subscription key header of Azure */ @get:JvmName("apiKey") val apiKey: String, ) { @@ -32,6 +103,16 @@ private constructor( } } + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.hanzo.ai`. + * + * The following other environments, with dedicated builder methods, are available: + * - sandbox: `https://api.sandbox.hanzo.ai` + */ + fun baseUrl(): String = baseUrl ?: PRODUCTION_URL + fun toBuilder() = Builder().from(this) companion object { @@ -51,6 +132,11 @@ private constructor( */ @JvmStatic fun builder() = Builder() + /** + * Returns options configured using system properties and environment variables. + * + * @see Builder.fromEnv + */ @JvmStatic fun fromEnv(): ClientOptions = builder().fromEnv().build() } @@ -60,8 +146,9 @@ private constructor( private var httpClient: HttpClient? = null private var checkJacksonVersionCompatibility: Boolean = true private var jsonMapper: JsonMapper = jsonMapper() + private var sleeper: Sleeper? = null private var clock: Clock = Clock.systemUTC() - private var baseUrl: String = PRODUCTION_URL + private var baseUrl: String? = null private var headers: Headers.Builder = Headers.builder() private var queryParams: QueryParams.Builder = QueryParams.builder() private var responseValidation: Boolean = false @@ -74,6 +161,7 @@ private constructor( httpClient = clientOptions.originalHttpClient checkJacksonVersionCompatibility = clientOptions.checkJacksonVersionCompatibility jsonMapper = clientOptions.jsonMapper + sleeper = clientOptions.sleeper clock = clientOptions.clock baseUrl = clientOptions.baseUrl headers = clientOptions.headers.toBuilder() @@ -84,26 +172,117 @@ private constructor( apiKey = clientOptions.apiKey } - fun httpClient(httpClient: HttpClient) = apply { this.httpClient = httpClient } + /** + * The HTTP client to use in the SDK. + * + * Use the one published in `hanzo-java-client-okhttp` or implement your own. + * + * This class takes ownership of the client and closes it when closed. + */ + fun httpClient(httpClient: HttpClient) = apply { + this.httpClient = PhantomReachableClosingHttpClient(httpClient) + } + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee + * that the SDK will work correctly when using an incompatible Jackson version. + */ fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { this.checkJacksonVersionCompatibility = checkJacksonVersionCompatibility } + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [ai.hanzo.api.core.jsonMapper]. The default is usually sufficient and rarely + * needs to be overridden. + */ fun jsonMapper(jsonMapper: JsonMapper) = apply { this.jsonMapper = jsonMapper } + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + fun sleeper(sleeper: Sleeper) = apply { this.sleeper = PhantomReachableSleeper(sleeper) } + + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ fun clock(clock: Clock) = apply { this.clock = clock } - fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl } + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.hanzo.ai`. + * + * The following other environments, with dedicated builder methods, are available: + * - sandbox: `https://api.sandbox.hanzo.ai` + */ + fun baseUrl(baseUrl: String?) = apply { this.baseUrl = baseUrl } + + /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ + fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) + + /** Sets [baseUrl] to `https://api.sandbox.hanzo.ai`. */ + fun sandbox() = baseUrl(SANDBOX_URL) + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ fun responseValidation(responseValidation: Boolean) = apply { this.responseValidation = responseValidation } + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ fun timeout(timeout: Timeout) = apply { this.timeout = timeout } + /** + * Sets the maximum time allowed for a complete HTTP call, not including retries. + * + * See [Timeout.request] for more details. + * + * For fine-grained control, pass a [Timeout] object. + */ + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) + + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } + /** The default name of the subscription key header of Azure */ fun apiKey(apiKey: String) = apply { this.apiKey = apiKey } fun headers(headers: Headers) = apply { @@ -186,7 +365,28 @@ private constructor( fun removeAllQueryParams(keys: Set) = apply { queryParams.removeAll(keys) } - fun fromEnv() = apply { System.getenv("HANZO_API_KEY")?.let { apiKey(it) } } + fun timeout(): Timeout = timeout + + /** + * Updates configuration using system properties and environment variables. + * + * See this table for the available options: + * + * | Setter | System property | Environment variable | Required | Default value | + * |-----------|-----------------|----------------------|----------|--------------------------| + * | `apiKey` | `hanzo.apiKey` | `HANZO_API_KEY` | true | - | + * | `baseUrl` | `hanzo.baseUrl` | `HANZO_BASE_URL` | true | `"https://api.hanzo.ai"` | + * + * System properties take precedence over environment variables. + */ + fun fromEnv() = apply { + (System.getProperty("hanzo.baseUrl") ?: System.getenv("HANZO_BASE_URL"))?.let { + baseUrl(it) + } + (System.getProperty("hanzo.apiKey") ?: System.getenv("HANZO_API_KEY"))?.let { + apiKey(it) + } + } /** * Returns an immutable instance of [ClientOptions]. @@ -203,6 +403,7 @@ private constructor( */ fun build(): ClientOptions { val httpClient = checkRequired("httpClient", httpClient) + val sleeper = sleeper ?: PhantomReachableSleeper(DefaultSleeper()) val apiKey = checkRequired("apiKey", apiKey) val headers = Headers.builder() @@ -214,9 +415,10 @@ private constructor( headers.put("X-Stainless-Package-Version", getPackageVersion()) headers.put("X-Stainless-Runtime", "JRE") headers.put("X-Stainless-Runtime-Version", getJavaVersion()) + headers.put("X-Stainless-Kotlin-Version", KotlinVersion.CURRENT.toString()) apiKey.let { if (!it.isEmpty()) { - headers.put("Ocp-Apim-Subscription-Key", it) + headers.put("x-litellm-api-key", it) } } headers.replaceAll(this.headers.build()) @@ -224,15 +426,15 @@ private constructor( return ClientOptions( httpClient, - PhantomReachableClosingHttpClient( - RetryingHttpClient.builder() - .httpClient(httpClient) - .clock(clock) - .maxRetries(maxRetries) - .build() - ), + RetryingHttpClient.builder() + .httpClient(httpClient) + .sleeper(sleeper) + .clock(clock) + .maxRetries(maxRetries) + .build(), checkJacksonVersionCompatibility, jsonMapper, + sleeper, clock, baseUrl, headers.build(), @@ -244,4 +446,19 @@ private constructor( ) } } + + /** + * Closes these client options, relinquishing any underlying resources. + * + * This is purposefully not inherited from [AutoCloseable] because the client options are + * long-lived and usually should not be synchronously closed via try-with-resources. + * + * It's also usually not necessary to call this method at all. the default client automatically + * releases threads and connections if they remain idle, but if you are writing an application + * that needs to aggressively release unused resources, then you may call this method. + */ + fun close() { + httpClient.close() + sleeper.close() + } } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/DefaultSleeper.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/DefaultSleeper.kt new file mode 100644 index 00000000..6b15ec7e --- /dev/null +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/DefaultSleeper.kt @@ -0,0 +1,28 @@ +package ai.hanzo.api.core + +import java.time.Duration +import java.util.Timer +import java.util.TimerTask +import java.util.concurrent.CompletableFuture + +class DefaultSleeper : Sleeper { + + private val timer = Timer("DefaultSleeper", true) + + override fun sleep(duration: Duration) = Thread.sleep(duration.toMillis()) + + override fun sleepAsync(duration: Duration): CompletableFuture { + val future = CompletableFuture() + timer.schedule( + object : TimerTask() { + override fun run() { + future.complete(null) + } + }, + duration.toMillis(), + ) + return future + } + + override fun close() = timer.cancel() +} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/ObjectMappers.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/ObjectMappers.kt index 6e6fc7e3..9c610872 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/ObjectMappers.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/ObjectMappers.kt @@ -4,23 +4,102 @@ package ai.hanzo.api.core import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.JsonParseException +import com.fasterxml.jackson.core.JsonParser +import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.MapperFeature import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.cfg.CoercionAction +import com.fasterxml.jackson.databind.cfg.CoercionInputShape +import com.fasterxml.jackson.databind.deser.std.StdDeserializer import com.fasterxml.jackson.databind.json.JsonMapper import com.fasterxml.jackson.databind.module.SimpleModule +import com.fasterxml.jackson.databind.type.LogicalType import com.fasterxml.jackson.datatype.jdk8.Jdk8Module import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.module.kotlin.kotlinModule import java.io.InputStream +import java.time.DateTimeException +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.OffsetDateTime +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoField fun jsonMapper(): JsonMapper = JsonMapper.builder() .addModule(kotlinModule()) .addModule(Jdk8Module()) .addModule(JavaTimeModule()) - .addModule(SimpleModule().addSerializer(InputStreamJsonSerializer)) + .addModule( + SimpleModule() + .addSerializer(InputStreamSerializer) + .addDeserializer(OffsetDateTime::class.java, LenientOffsetDateTimeDeserializer()) + ) + .withCoercionConfig(LogicalType.Boolean) { + it.setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Integer) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Float) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Textual) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.DateTime) { + it.setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Array) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Collection) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Map) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.POJO) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + } .serializationInclusion(JsonInclude.Include.NON_ABSENT) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) .disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE) @@ -34,7 +113,10 @@ fun jsonMapper(): JsonMapper = .disable(MapperFeature.AUTO_DETECT_SETTERS) .build() -private object InputStreamJsonSerializer : BaseSerializer(InputStream::class) { +/** A serializer that serializes [InputStream] to bytes. */ +private object InputStreamSerializer : BaseSerializer(InputStream::class) { + + private fun readResolve(): Any = InputStreamSerializer override fun serialize( value: InputStream?, @@ -48,3 +130,49 @@ private object InputStreamJsonSerializer : BaseSerializer(InputStre } } } + +/** + * A deserializer that can deserialize [OffsetDateTime] from datetimes, dates, and zoned datetimes. + */ +private class LenientOffsetDateTimeDeserializer : + StdDeserializer(OffsetDateTime::class.java) { + + companion object { + + private val DATE_TIME_FORMATTERS = + listOf( + DateTimeFormatter.ISO_LOCAL_DATE_TIME, + DateTimeFormatter.ISO_LOCAL_DATE, + DateTimeFormatter.ISO_ZONED_DATE_TIME, + ) + } + + override fun logicalType(): LogicalType = LogicalType.DateTime + + override fun deserialize(p: JsonParser, context: DeserializationContext): OffsetDateTime { + val exceptions = mutableListOf() + + for (formatter in DATE_TIME_FORMATTERS) { + try { + val temporal = formatter.parse(p.text) + + return when { + !temporal.isSupported(ChronoField.HOUR_OF_DAY) -> + LocalDate.from(temporal) + .atStartOfDay() + .atZone(ZoneId.of("UTC")) + .toOffsetDateTime() + !temporal.isSupported(ChronoField.OFFSET_SECONDS) -> + LocalDateTime.from(temporal).atZone(ZoneId.of("UTC")).toOffsetDateTime() + else -> OffsetDateTime.from(temporal) + } + } catch (e: DateTimeException) { + exceptions.add(e) + } + } + + throw JsonParseException(p, "Cannot parse `OffsetDateTime` from value: ${p.text}").apply { + exceptions.forEach { addSuppressed(it) } + } + } +} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/PhantomReachableExecutorService.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/PhantomReachableExecutorService.kt new file mode 100644 index 00000000..a95108d7 --- /dev/null +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/PhantomReachableExecutorService.kt @@ -0,0 +1,58 @@ +package ai.hanzo.api.core + +import java.util.concurrent.Callable +import java.util.concurrent.ExecutorService +import java.util.concurrent.Future +import java.util.concurrent.TimeUnit + +/** + * A delegating wrapper around an [ExecutorService] that shuts it down once it's only phantom + * reachable. + * + * This class ensures the [ExecutorService] is shut down even if the user forgets to do it. + */ +internal class PhantomReachableExecutorService(private val executorService: ExecutorService) : + ExecutorService { + init { + closeWhenPhantomReachable(this) { executorService.shutdown() } + } + + override fun execute(command: Runnable) = executorService.execute(command) + + override fun shutdown() = executorService.shutdown() + + override fun shutdownNow(): MutableList = executorService.shutdownNow() + + override fun isShutdown(): Boolean = executorService.isShutdown + + override fun isTerminated(): Boolean = executorService.isTerminated + + override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean = + executorService.awaitTermination(timeout, unit) + + override fun submit(task: Callable): Future = executorService.submit(task) + + override fun submit(task: Runnable, result: T): Future = + executorService.submit(task, result) + + override fun submit(task: Runnable): Future<*> = executorService.submit(task) + + override fun invokeAll( + tasks: MutableCollection> + ): MutableList> = executorService.invokeAll(tasks) + + override fun invokeAll( + tasks: MutableCollection>, + timeout: Long, + unit: TimeUnit, + ): MutableList> = executorService.invokeAll(tasks, timeout, unit) + + override fun invokeAny(tasks: MutableCollection>): T = + executorService.invokeAny(tasks) + + override fun invokeAny( + tasks: MutableCollection>, + timeout: Long, + unit: TimeUnit, + ): T = executorService.invokeAny(tasks, timeout, unit) +} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/PhantomReachableSleeper.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/PhantomReachableSleeper.kt new file mode 100644 index 00000000..5effc26d --- /dev/null +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/PhantomReachableSleeper.kt @@ -0,0 +1,23 @@ +package ai.hanzo.api.core + +import java.time.Duration +import java.util.concurrent.CompletableFuture + +/** + * A delegating wrapper around a [Sleeper] that closes it once it's only phantom reachable. + * + * This class ensures the [Sleeper] is closed even if the user forgets to do it. + */ +internal class PhantomReachableSleeper(private val sleeper: Sleeper) : Sleeper { + + init { + closeWhenPhantomReachable(this, sleeper) + } + + override fun sleep(duration: Duration) = sleeper.sleep(duration) + + override fun sleepAsync(duration: Duration): CompletableFuture = + sleeper.sleepAsync(duration) + + override fun close() = sleeper.close() +} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Properties.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Properties.kt index decba931..70e2d21a 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Properties.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Properties.kt @@ -2,7 +2,7 @@ package ai.hanzo.api.core -import java.util.Properties +import ai.hanzo.api.client.HanzoClient fun getOsArch(): String { val osArch = System.getProperty("os.arch") @@ -16,7 +16,7 @@ fun getOsArch(): String { "x86_64" -> "x64" "arm" -> "arm" "aarch64" -> "arm64" - else -> "other:${osArch}" + else -> "other:$osArch" } } @@ -30,13 +30,13 @@ fun getOsName(): String { osName.startsWith("Linux") -> "Linux" osName.startsWith("Mac OS") -> "MacOS" osName.startsWith("Windows") -> "Windows" - else -> "Other:${osName}" + else -> "Other:$osName" } } fun getOsVersion(): String = System.getProperty("os.version", "unknown") fun getPackageVersion(): String = - Properties::class.java.`package`.implementationVersion ?: "unknown" + HanzoClient::class.java.`package`.implementationVersion ?: "unknown" fun getJavaVersion(): String = System.getProperty("java.version", "unknown") diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Sleeper.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Sleeper.kt new file mode 100644 index 00000000..e08c7205 --- /dev/null +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Sleeper.kt @@ -0,0 +1,21 @@ +package ai.hanzo.api.core + +import java.time.Duration +import java.util.concurrent.CompletableFuture + +/** + * An interface for delaying execution for a specified amount of time. + * + * Useful for testing and cleaning up resources. + */ +interface Sleeper : AutoCloseable { + + /** Synchronously pauses execution for the given [duration]. */ + fun sleep(duration: Duration) + + /** Asynchronously pauses execution for the given [duration]. */ + fun sleepAsync(duration: Duration): CompletableFuture + + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ + override fun close() +} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Timeout.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Timeout.kt index 844fb638..ba32882f 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Timeout.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Timeout.kt @@ -157,10 +157,14 @@ private constructor( return true } - return /* spotless:off */ other is Timeout && connect == other.connect && read == other.read && write == other.write && request == other.request /* spotless:on */ + return other is Timeout && + connect == other.connect && + read == other.read && + write == other.write && + request == other.request } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(connect, read, write, request) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(connect, read, write, request) override fun toString() = "Timeout{connect=$connect, read=$read, write=$write, request=$request}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Utils.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Utils.kt index 5348d056..75457e0c 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Utils.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Utils.kt @@ -5,6 +5,8 @@ package ai.hanzo.api.core import ai.hanzo.api.errors.HanzoInvalidDataException import java.util.Collections import java.util.SortedMap +import java.util.concurrent.CompletableFuture +import java.util.concurrent.locks.Lock @JvmSynthetic internal fun T?.getOrThrow(name: String): T = @@ -25,6 +27,34 @@ internal fun , V> SortedMap.toImmutable(): SortedMap> Sequence.allMaxBy(selector: (T) -> R): List { + var maxValue: R? = null + val maxElements = mutableListOf() + + val iterator = iterator() + while (iterator.hasNext()) { + val element = iterator.next() + val value = selector(element) + if (maxValue == null || value > maxValue) { + maxValue = value + maxElements.clear() + maxElements.add(element) + } else if (value == maxValue) { + maxElements.add(element) + } + } + + return maxElements +} + /** * Returns whether [this] is equal to [other]. * @@ -62,3 +92,24 @@ internal fun Any?.contentToString(): String { } internal interface Enum + +/** + * Executes the given [action] while holding the lock, returning a [CompletableFuture] with the + * result. + * + * @param action The asynchronous action to execute while holding the lock + * @return A [CompletableFuture] that completes with the result of the action + */ +@JvmSynthetic +internal fun Lock.withLockAsync(action: () -> CompletableFuture): CompletableFuture { + lock() + val future = + try { + action() + } catch (e: Throwable) { + unlock() + throw e + } + future.whenComplete { _, _ -> unlock() } + return future +} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Values.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Values.kt index a7334087..0e5ad6e4 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Values.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/Values.kt @@ -29,30 +29,51 @@ import java.io.InputStream import java.util.Objects import java.util.Optional +/** + * A class representing a serializable JSON field. + * + * It can either be a [KnownValue] value of type [T], matching the type the SDK expects, or an + * arbitrary JSON value that bypasses the type system (via [JsonValue]). + */ @JsonDeserialize(using = JsonField.Deserializer::class) sealed class JsonField { + /** + * Returns whether this field is missing, which means it will be omitted from the serialized + * JSON entirely. + */ fun isMissing(): Boolean = this is JsonMissing + /** Whether this field is explicitly set to `null`. */ fun isNull(): Boolean = this is JsonNull - fun asKnown(): Optional = - when (this) { - is KnownValue -> Optional.of(value) - else -> Optional.empty() - } + /** + * Returns an [Optional] containing this field's "known" value, meaning it matches the type the + * SDK expects, or an empty [Optional] if this field contains an arbitrary [JsonValue]. + * + * This is the opposite of [asUnknown]. + */ + fun asKnown(): + Optional< + // Safe because `Optional` is effectively covariant, but Kotlin doesn't know that. + @UnsafeVariance + T + > = Optional.ofNullable((this as? KnownValue)?.value) /** - * If the "known" value (i.e. matching the type that the SDK expects) is returned by the API - * then this method will return an empty `Optional`, otherwise the returned `Optional` is given - * a `JsonValue`. + * Returns an [Optional] containing this field's arbitrary [JsonValue], meaning it mismatches + * the type the SDK expects, or an empty [Optional] if this field contains a "known" value. + * + * This is the opposite of [asKnown]. */ - fun asUnknown(): Optional = - when (this) { - is JsonValue -> Optional.of(this) - else -> Optional.empty() - } + fun asUnknown(): Optional = Optional.ofNullable(this as? JsonValue) + /** + * Returns an [Optional] containing this field's boolean value, or an empty [Optional] if it + * doesn't contain a boolean. + * + * This method checks for both a [KnownValue] containing a boolean and for [JsonBoolean]. + */ fun asBoolean(): Optional = when (this) { is JsonBoolean -> Optional.of(value) @@ -60,6 +81,12 @@ sealed class JsonField { else -> Optional.empty() } + /** + * Returns an [Optional] containing this field's numerical value, or an empty [Optional] if it + * doesn't contain a number. + * + * This method checks for both a [KnownValue] containing a number and for [JsonNumber]. + */ fun asNumber(): Optional = when (this) { is JsonNumber -> Optional.of(value) @@ -67,6 +94,12 @@ sealed class JsonField { else -> Optional.empty() } + /** + * Returns an [Optional] containing this field's string value, or an empty [Optional] if it + * doesn't contain a string. + * + * This method checks for both a [KnownValue] containing a string and for [JsonString]. + */ fun asString(): Optional = when (this) { is JsonString -> Optional.of(value) @@ -77,6 +110,12 @@ sealed class JsonField { fun asStringOrThrow(): String = asString().orElseThrow { HanzoInvalidDataException("Value is not a string") } + /** + * Returns an [Optional] containing this field's list value, or an empty [Optional] if it + * doesn't contain a list. + * + * This method checks for both a [KnownValue] containing a list and for [JsonArray]. + */ fun asArray(): Optional> = when (this) { is JsonArray -> Optional.of(values) @@ -95,6 +134,12 @@ sealed class JsonField { else -> Optional.empty() } + /** + * Returns an [Optional] containing this field's map value, or an empty [Optional] if it doesn't + * contain a map. + * + * This method checks for both a [KnownValue] containing a map and for [JsonObject]. + */ fun asObject(): Optional> = when (this) { is JsonObject -> Optional.of(values) @@ -132,11 +177,17 @@ sealed class JsonField { } @JvmSynthetic - internal fun getNullable(name: String): T? = + internal fun getOptional( + name: String + ): Optional< + // Safe because `Optional` is effectively covariant, but Kotlin doesn't know that. + @UnsafeVariance + T + > = when (this) { - is KnownValue -> value - is JsonMissing -> null - is JsonNull -> null + is KnownValue -> Optional.of(value) + is JsonMissing, + is JsonNull -> Optional.empty() else -> throw HanzoInvalidDataException("`$name` is invalid, received $this") } @@ -147,21 +198,33 @@ sealed class JsonField { is JsonValue -> this } - @JvmSynthetic fun accept(consume: (T) -> Unit) = asKnown().ifPresent(consume) + @JvmSynthetic internal fun accept(consume: (T) -> Unit) = asKnown().ifPresent(consume) + /** Returns the result of calling the [visitor] method corresponding to this field's state. */ fun accept(visitor: Visitor): R = when (this) { is KnownValue -> visitor.visitKnown(value) is JsonValue -> accept(visitor as JsonValue.Visitor) } + /** + * An interface that defines how to map each possible state of a `JsonField` to a value of + * type [R]. + */ interface Visitor : JsonValue.Visitor { + fun visitKnown(value: T): R = visitDefault() } companion object { + + /** Returns a [JsonField] containing the given "known" [value]. */ @JvmStatic fun of(value: T): JsonField = KnownValue.of(value) + /** + * Returns a [JsonField] containing the given "known" [value], or [JsonNull] if [value] is + * null. + */ @JvmStatic fun ofNullable(value: T?): JsonField = when (value) { @@ -176,6 +239,7 @@ sealed class JsonField { * annotation. */ class IsMissing { + override fun equals(other: Any?): Boolean = other is JsonMissing override fun hashCode(): Int = Objects.hash() @@ -197,6 +261,12 @@ sealed class JsonField { } } +/** + * A class representing an arbitrary JSON value. + * + * It is immutable and assignable to any [JsonField], regardless of its expected type (i.e. its + * generic type argument). + */ @JsonDeserialize(using = JsonValue.Deserializer::class) sealed class JsonValue : JsonField() { @@ -204,6 +274,7 @@ sealed class JsonValue : JsonField() { fun convert(type: Class): R? = JSON_MAPPER.convertValue(this, type) + /** Returns the result of calling the [visitor] method corresponding to this value's variant. */ fun accept(visitor: Visitor): R = when (this) { is JsonMissing -> visitor.visitMissing() @@ -215,7 +286,12 @@ sealed class JsonValue : JsonField() { is JsonObject -> visitor.visitObject(values) } + /** + * An interface that defines how to map each variant state of a [JsonValue] to a value of type + * [R]. + */ interface Visitor { + fun visitNull(): R = visitDefault() fun visitMissing(): R = visitDefault() @@ -230,15 +306,52 @@ sealed class JsonValue : JsonField() { fun visitObject(values: Map): R = visitDefault() - fun visitDefault(): R { - throw RuntimeException("Unexpected value") - } + /** + * The default implementation for unimplemented visitor methods. + * + * @throws IllegalArgumentException in the default implementation. + */ + fun visitDefault(): R = throw IllegalArgumentException("Unexpected value") } companion object { private val JSON_MAPPER = jsonMapper() + /** + * Converts the given [value] to a [JsonValue]. + * + * This method works best on primitive types, [List] values, [Map] values, and nested + * combinations of these. For example: + * ```java + * // Create primitive JSON values + * JsonValue nullValue = JsonValue.from(null); + * JsonValue booleanValue = JsonValue.from(true); + * JsonValue numberValue = JsonValue.from(42); + * JsonValue stringValue = JsonValue.from("Hello World!"); + * + * // Create a JSON array value equivalent to `["Hello", "World"]` + * JsonValue arrayValue = JsonValue.from(List.of("Hello", "World")); + * + * // Create a JSON object value equivalent to `{ "a": 1, "b": 2 }` + * JsonValue objectValue = JsonValue.from(Map.of( + * "a", 1, + * "b", 2 + * )); + * + * // Create an arbitrarily nested JSON equivalent to: + * // { + * // "a": [1, 2], + * // "b": [3, 4] + * // } + * JsonValue complexValue = JsonValue.from(Map.of( + * "a", List.of(1, 2), + * "b", List.of(3, 4) + * )); + * ``` + * + * @throws IllegalArgumentException if [value] is not JSON serializable. + */ @JvmStatic fun from(value: Any?): JsonValue = when (value) { @@ -247,6 +360,11 @@ sealed class JsonValue : JsonField() { else -> JSON_MAPPER.convertValue(value, JsonValue::class.java) } + /** + * Returns a [JsonValue] converted from the given Jackson [JsonNode]. + * + * @throws IllegalStateException for unsupported node types. + */ @JvmStatic fun fromJsonNode(node: JsonNode): JsonValue = when (node.nodeType) { @@ -268,12 +386,19 @@ sealed class JsonValue : JsonField() { } class Deserializer : BaseDeserializer(JsonValue::class) { + override fun ObjectCodec.deserialize(node: JsonNode): JsonValue = fromJsonNode(node) override fun getNullValue(context: DeserializationContext?): JsonValue = JsonNull.of() } } +/** + * A class representing a "known" JSON serializable value of type [T], matching the type the SDK + * expects. + * + * It is assignable to `JsonField`. + */ class KnownValue private constructor( @com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: T @@ -292,44 +417,59 @@ private constructor( override fun toString() = value.contentToString() companion object { + + /** Returns a [KnownValue] containing the given [value]. */ @JsonCreator @JvmStatic fun of(value: T) = KnownValue(value) } } +/** + * A [JsonValue] representing an omitted JSON field. + * + * An instance of this class will cause a JSON field to be omitted from the serialized JSON + * entirely. + */ @JsonSerialize(using = JsonMissing.Serializer::class) class JsonMissing : JsonValue() { override fun toString() = "" companion object { + private val INSTANCE: JsonMissing = JsonMissing() + /** Returns the singleton instance of [JsonMissing]. */ @JvmStatic fun of() = INSTANCE } class Serializer : BaseSerializer(JsonMissing::class) { + override fun serialize( value: JsonMissing, generator: JsonGenerator, provider: SerializerProvider, ) { - throw RuntimeException("JsonMissing cannot be serialized") + throw IllegalStateException("JsonMissing cannot be serialized") } } } +/** A [JsonValue] representing a JSON `null` value. */ @JsonSerialize(using = NullSerializer::class) class JsonNull : JsonValue() { override fun toString() = "null" companion object { + private val INSTANCE: JsonNull = JsonNull() + /** Returns the singleton instance of [JsonMissing]. */ @JsonCreator @JvmStatic fun of() = INSTANCE } } +/** A [JsonValue] representing a JSON boolean value. */ class JsonBoolean private constructor( @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: Boolean @@ -348,14 +488,18 @@ private constructor( override fun toString() = value.toString() companion object { + + /** Returns a [JsonBoolean] containing the given [value]. */ @JsonCreator @JvmStatic fun of(value: Boolean) = JsonBoolean(value) } } +/** A [JsonValue] representing a JSON number value. */ class JsonNumber private constructor( @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: Number ) : JsonValue() { + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -369,10 +513,13 @@ private constructor( override fun toString() = value.toString() companion object { + + /** Returns a [JsonNumber] containing the given [value]. */ @JsonCreator @JvmStatic fun of(value: Number) = JsonNumber(value) } } +/** A [JsonValue] representing a JSON string value. */ class JsonString private constructor( @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: String @@ -391,10 +538,13 @@ private constructor( override fun toString() = value companion object { + + /** Returns a [JsonString] containing the given [value]. */ @JsonCreator @JvmStatic fun of(value: String) = JsonString(value) } } +/** A [JsonValue] representing a JSON array value. */ class JsonArray private constructor( @get:com.fasterxml.jackson.annotation.JsonValue @@ -415,10 +565,13 @@ private constructor( override fun toString() = values.toString() companion object { + + /** Returns a [JsonArray] containing the given [values]. */ @JsonCreator @JvmStatic fun of(values: List) = JsonArray(values.toImmutable()) } } +/** A [JsonValue] representing a JSON object value. */ class JsonObject private constructor( @get:com.fasterxml.jackson.annotation.JsonValue @@ -439,32 +592,62 @@ private constructor( override fun toString() = values.toString() companion object { + + /** Returns a [JsonObject] containing the given [values]. */ @JsonCreator @JvmStatic fun of(values: Map) = JsonObject(values.toImmutable()) } } +/** A Jackson annotation for excluding fields set to [JsonMissing] from the serialized JSON. */ @JacksonAnnotationsInside @JsonInclude(JsonInclude.Include.CUSTOM, valueFilter = JsonField.IsMissing::class) annotation class ExcludeMissing +/** A class representing a field in a `multipart/form-data` request. */ class MultipartField private constructor( + /** A [JsonField] value, which will be serialized to zero or more parts. */ @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: JsonField, + /** A content type for the serialized parts. */ @get:JvmName("contentType") val contentType: String, private val filename: String?, ) { companion object { + /** + * Returns a [MultipartField] containing the given [value] as a [KnownValue]. + * + * [contentType] will be set to `application/octet-stream` if [value] is binary data, or + * `text/plain; charset=utf-8` otherwise. + */ @JvmStatic fun of(value: T?) = builder().value(value).build() + /** + * Returns a [MultipartField] containing the given [value]. + * + * [contentType] will be set to `application/octet-stream` if [value] is binary data, or + * `text/plain; charset=utf-8` otherwise. + */ @JvmStatic fun of(value: JsonField) = builder().value(value).build() + /** + * Returns a mutable builder for constructing an instance of [MultipartField]. + * + * The following fields are required: + * ```java + * .value() + * ``` + * + * If [contentType] is unset, then it will be set to `application/octet-stream` if [value] + * is binary data, or `text/plain; charset=utf-8` otherwise. + */ @JvmStatic fun builder() = Builder() } + /** Returns the filename directive that will be included in the serialized field. */ fun filename(): Optional = Optional.ofNullable(filename) @JvmSynthetic @@ -486,8 +669,24 @@ private constructor( fun filename(filename: String?) = apply { this.filename = filename } + /** Alias for calling [Builder.filename] with `filename.orElse(null)`. */ fun filename(filename: Optional) = filename(filename.orElse(null)) + /** + * Returns an immutable instance of [MultipartField]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .value() + * ``` + * + * If [contentType] is unset, then it will be set to `application/octet-stream` if [value] + * is binary data, or `text/plain; charset=utf-8` otherwise. + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): MultipartField { val value = checkRequired("value", value) return MultipartField( diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/handlers/ErrorHandler.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/handlers/ErrorHandler.kt index d9b86af9..f3d71314 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/handlers/ErrorHandler.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/handlers/ErrorHandler.kt @@ -19,7 +19,7 @@ import ai.hanzo.api.errors.UnprocessableEntityException import com.fasterxml.jackson.databind.json.JsonMapper @JvmSynthetic -internal fun errorHandler(jsonMapper: JsonMapper): Handler { +internal fun errorBodyHandler(jsonMapper: JsonMapper): Handler { val handler = jsonHandler(jsonMapper) return object : Handler { @@ -33,52 +33,52 @@ internal fun errorHandler(jsonMapper: JsonMapper): Handler { } @JvmSynthetic -internal fun Handler.withErrorHandler(errorHandler: Handler): Handler = - object : Handler { - override fun handle(response: HttpResponse): T = +internal fun errorHandler(errorBodyHandler: Handler): Handler = + object : Handler { + override fun handle(response: HttpResponse): HttpResponse = when (val statusCode = response.statusCode()) { - in 200..299 -> this@withErrorHandler.handle(response) + in 200..299 -> response 400 -> throw BadRequestException.builder() .headers(response.headers()) - .body(errorHandler.handle(response)) + .body(errorBodyHandler.handle(response)) .build() 401 -> throw UnauthorizedException.builder() .headers(response.headers()) - .body(errorHandler.handle(response)) + .body(errorBodyHandler.handle(response)) .build() 403 -> throw PermissionDeniedException.builder() .headers(response.headers()) - .body(errorHandler.handle(response)) + .body(errorBodyHandler.handle(response)) .build() 404 -> throw NotFoundException.builder() .headers(response.headers()) - .body(errorHandler.handle(response)) + .body(errorBodyHandler.handle(response)) .build() 422 -> throw UnprocessableEntityException.builder() .headers(response.headers()) - .body(errorHandler.handle(response)) + .body(errorBodyHandler.handle(response)) .build() 429 -> throw RateLimitException.builder() .headers(response.headers()) - .body(errorHandler.handle(response)) + .body(errorBodyHandler.handle(response)) .build() in 500..599 -> throw InternalServerException.builder() .statusCode(statusCode) .headers(response.headers()) - .body(errorHandler.handle(response)) + .body(errorBodyHandler.handle(response)) .build() else -> throw UnexpectedStatusCodeException.builder() .statusCode(statusCode) .headers(response.headers()) - .body(errorHandler.handle(response)) + .body(errorBodyHandler.handle(response)) .build() } } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/AsyncStreamResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/AsyncStreamResponse.kt new file mode 100644 index 00000000..9cfd82c9 --- /dev/null +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/AsyncStreamResponse.kt @@ -0,0 +1,157 @@ +package ai.hanzo.api.core.http + +import ai.hanzo.api.core.http.AsyncStreamResponse.Handler +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.concurrent.atomic.AtomicReference + +/** + * A class providing access to an API response as an asynchronous stream of chunks of type [T], + * where each chunk can be individually processed as soon as it arrives instead of waiting on the + * full response. + */ +interface AsyncStreamResponse { + + /** + * Registers [handler] to be called for events of this stream. + * + * [handler]'s methods will be called in the client's configured or default thread pool. + * + * @throws IllegalStateException if [subscribe] has already been called. + */ + fun subscribe(handler: Handler): AsyncStreamResponse + + /** + * Registers [handler] to be called for events of this stream. + * + * [handler]'s methods will be called in the given [executor]. + * + * @throws IllegalStateException if [subscribe] has already been called. + */ + fun subscribe(handler: Handler, executor: Executor): AsyncStreamResponse + + /** + * Returns a future that completes when a stream is fully consumed, errors, or gets closed + * early. + */ + fun onCompleteFuture(): CompletableFuture + + /** + * Closes this resource, relinquishing any underlying resources. + * + * This is purposefully not inherited from [AutoCloseable] because this response should not be + * synchronously closed via try-with-resources. + */ + fun close() + + /** A class for handling streaming events. */ + fun interface Handler { + + /** Called whenever a chunk is received. */ + fun onNext(value: T) + + /** + * Called when a stream is fully consumed, errors, or gets closed early. + * + * [onNext] will not be called once this method is called. + * + * @param error Non-empty if the stream completed due to an error. + */ + fun onComplete(error: Optional) {} + } +} + +@JvmSynthetic +internal fun CompletableFuture>.toAsync(streamHandlerExecutor: Executor) = + PhantomReachableClosingAsyncStreamResponse( + object : AsyncStreamResponse { + + private val onCompleteFuture = CompletableFuture() + private val state = AtomicReference(State.NEW) + + init { + this@toAsync.whenComplete { _, error -> + // If an error occurs from the original future, then we should resolve the + // `onCompleteFuture` even if `subscribe` has not been called. + error?.let(onCompleteFuture::completeExceptionally) + } + } + + override fun subscribe(handler: Handler): AsyncStreamResponse = + subscribe(handler, streamHandlerExecutor) + + override fun subscribe( + handler: Handler, + executor: Executor, + ): AsyncStreamResponse = apply { + // TODO(JDK): Use `compareAndExchange` once targeting JDK 9. + check(state.compareAndSet(State.NEW, State.SUBSCRIBED)) { + if (state.get() == State.SUBSCRIBED) "Cannot subscribe more than once" + else "Cannot subscribe after the response is closed" + } + + this@toAsync.whenCompleteAsync( + { streamResponse, futureError -> + if (state.get() == State.CLOSED) { + // Avoid doing any work if `close` was called before the future + // completed. + return@whenCompleteAsync + } + + if (futureError != null) { + // An error occurred before we started passing chunks to the handler. + handler.onComplete(Optional.of(futureError)) + return@whenCompleteAsync + } + + var streamError: Throwable? = null + try { + streamResponse.stream().forEach(handler::onNext) + } catch (e: Throwable) { + streamError = e + } + + try { + handler.onComplete(Optional.ofNullable(streamError)) + } finally { + try { + // Notify completion via the `onCompleteFuture` as well. This is in + // a separate `try-finally` block so that we still complete the + // future if `handler.onComplete` throws. + if (streamError == null) { + onCompleteFuture.complete(null) + } else { + onCompleteFuture.completeExceptionally(streamError) + } + } finally { + close() + } + } + }, + executor, + ) + } + + override fun onCompleteFuture(): CompletableFuture = onCompleteFuture + + override fun close() { + val previousState = state.getAndSet(State.CLOSED) + if (previousState == State.CLOSED) { + return + } + + this@toAsync.whenComplete { streamResponse, error -> streamResponse?.close() } + // When the stream is closed, we should always consider it closed. If it closed due + // to an error, then we will have already completed the future earlier, and this + // will be a no-op. + onCompleteFuture.complete(null) + } + } + ) + +private enum class State { + NEW, + SUBSCRIBED, + CLOSED, +} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/Headers.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/Headers.kt index 3958ec95..a05f1289 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/Headers.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/Headers.kt @@ -1,5 +1,15 @@ +// File generated from our OpenAPI spec by Stainless. + package ai.hanzo.api.core.http +import ai.hanzo.api.core.JsonArray +import ai.hanzo.api.core.JsonBoolean +import ai.hanzo.api.core.JsonMissing +import ai.hanzo.api.core.JsonNull +import ai.hanzo.api.core.JsonNumber +import ai.hanzo.api.core.JsonObject +import ai.hanzo.api.core.JsonString +import ai.hanzo.api.core.JsonValue import ai.hanzo.api.core.toImmutable import java.util.TreeMap @@ -28,6 +38,19 @@ private constructor( TreeMap(String.CASE_INSENSITIVE_ORDER) private var size: Int = 0 + fun put(name: String, value: JsonValue): Builder = apply { + when (value) { + is JsonMissing, + is JsonNull -> {} + is JsonBoolean -> put(name, value.value.toString()) + is JsonNumber -> put(name, value.value.toString()) + is JsonString -> put(name, value.value) + is JsonArray -> value.values.forEach { put(name, it) } + is JsonObject -> + value.values.forEach { (nestedName, value) -> put("$name.$nestedName", value) } + } + } + fun put(name: String, value: String) = apply { map.getOrPut(name) { mutableListOf() }.add(value) size++ @@ -41,15 +64,6 @@ private constructor( headers.names().forEach { put(it, headers.values(it)) } } - fun remove(name: String) = apply { size -= map.remove(name).orEmpty().size } - - fun removeAll(names: Set) = apply { names.forEach(::remove) } - - fun clear() = apply { - map.clear() - size = 0 - } - fun replace(name: String, value: String) = apply { remove(name) put(name, value) @@ -68,6 +82,15 @@ private constructor( headers.names().forEach { replace(it, headers.values(it)) } } + fun remove(name: String) = apply { size -= map.remove(name).orEmpty().size } + + fun removeAll(names: Set) = apply { names.forEach(::remove) } + + fun clear() = apply { + map.clear() + size = 0 + } + fun build() = Headers( map.mapValuesTo(TreeMap(String.CASE_INSENSITIVE_ORDER)) { (_, values) -> diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/HttpRequest.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/HttpRequest.kt index 94495ca6..04404fbc 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/HttpRequest.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/HttpRequest.kt @@ -2,21 +2,51 @@ package ai.hanzo.api.core.http import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.toImmutable +import java.net.URLEncoder class HttpRequest private constructor( @get:JvmName("method") val method: HttpMethod, - @get:JvmName("url") val url: String?, + @get:JvmName("baseUrl") val baseUrl: String, @get:JvmName("pathSegments") val pathSegments: List, @get:JvmName("headers") val headers: Headers, @get:JvmName("queryParams") val queryParams: QueryParams, @get:JvmName("body") val body: HttpRequestBody?, ) { + fun url(): String = buildString { + append(baseUrl) + + pathSegments.forEach { segment -> + if (!endsWith("/")) { + append("/") + } + append(URLEncoder.encode(segment, "UTF-8")) + } + + if (queryParams.isEmpty()) { + return@buildString + } + + append("?") + var isFirst = true + queryParams.keys().forEach { key -> + queryParams.values(key).forEach { value -> + if (!isFirst) { + append("&") + } + append(URLEncoder.encode(key, "UTF-8")) + append("=") + append(URLEncoder.encode(value, "UTF-8")) + isFirst = false + } + } + } + fun toBuilder(): Builder = Builder().from(this) override fun toString(): String = - "HttpRequest{method=$method, url=$url, pathSegments=$pathSegments, headers=$headers, queryParams=$queryParams, body=$body}" + "HttpRequest{method=$method, baseUrl=$baseUrl, pathSegments=$pathSegments, headers=$headers, queryParams=$queryParams, body=$body}" companion object { @JvmStatic fun builder() = Builder() @@ -25,7 +55,7 @@ private constructor( class Builder internal constructor() { private var method: HttpMethod? = null - private var url: String? = null + private var baseUrl: String? = null private var pathSegments: MutableList = mutableListOf() private var headers: Headers.Builder = Headers.builder() private var queryParams: QueryParams.Builder = QueryParams.builder() @@ -34,7 +64,7 @@ private constructor( @JvmSynthetic internal fun from(request: HttpRequest) = apply { method = request.method - url = request.url + baseUrl = request.baseUrl pathSegments = request.pathSegments.toMutableList() headers = request.headers.toBuilder() queryParams = request.queryParams.toBuilder() @@ -43,7 +73,7 @@ private constructor( fun method(method: HttpMethod) = apply { this.method = method } - fun url(url: String) = apply { this.url = url } + fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl } fun addPathSegment(pathSegment: String) = apply { pathSegments.add(pathSegment) } @@ -136,7 +166,7 @@ private constructor( fun build(): HttpRequest = HttpRequest( checkRequired("method", method), - url, + checkRequired("baseUrl", baseUrl), pathSegments.toImmutable(), headers.build(), queryParams.build(), diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/HttpResponseFor.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/HttpResponseFor.kt index f22c643a..f8b25335 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/HttpResponseFor.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/HttpResponseFor.kt @@ -11,7 +11,9 @@ interface HttpResponseFor : HttpResponse { internal fun HttpResponse.parseable(parse: () -> T): HttpResponseFor = object : HttpResponseFor { - override fun parse(): T = parse() + private val parsed: T by lazy { parse() } + + override fun parse(): T = parsed override fun statusCode(): Int = this@parseable.statusCode() diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/PhantomReachableClosingAsyncStreamResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/PhantomReachableClosingAsyncStreamResponse.kt new file mode 100644 index 00000000..3949c757 --- /dev/null +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/PhantomReachableClosingAsyncStreamResponse.kt @@ -0,0 +1,56 @@ +package ai.hanzo.api.core.http + +import ai.hanzo.api.core.closeWhenPhantomReachable +import ai.hanzo.api.core.http.AsyncStreamResponse.Handler +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor + +/** + * A delegating wrapper around an `AsyncStreamResponse` that closes it once it's only phantom + * reachable. + * + * This class ensures the `AsyncStreamResponse` is closed even if the user forgets to close it. + */ +internal class PhantomReachableClosingAsyncStreamResponse( + private val asyncStreamResponse: AsyncStreamResponse +) : AsyncStreamResponse { + + /** + * An object used for keeping `asyncStreamResponse` open while the object is still reachable. + */ + private val reachabilityTracker = Object() + + init { + closeWhenPhantomReachable(reachabilityTracker, asyncStreamResponse::close) + } + + override fun subscribe(handler: Handler): AsyncStreamResponse = apply { + asyncStreamResponse.subscribe(TrackedHandler(handler, reachabilityTracker)) + } + + override fun subscribe(handler: Handler, executor: Executor): AsyncStreamResponse = + apply { + asyncStreamResponse.subscribe(TrackedHandler(handler, reachabilityTracker), executor) + } + + override fun onCompleteFuture(): CompletableFuture = + asyncStreamResponse.onCompleteFuture() + + override fun close() = asyncStreamResponse.close() +} + +/** + * A wrapper around a `Handler` that also references a `reachabilityTracker` object. + * + * Referencing the `reachabilityTracker` object prevents it from getting reclaimed while the handler + * is still reachable. + */ +private class TrackedHandler( + private val handler: Handler, + private val reachabilityTracker: Any, +) : Handler { + override fun onNext(value: T) = handler.onNext(value) + + override fun onComplete(error: Optional) = handler.onComplete(error) +} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/PhantomReachableClosingStreamResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/PhantomReachableClosingStreamResponse.kt new file mode 100644 index 00000000..8c59c3cd --- /dev/null +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/PhantomReachableClosingStreamResponse.kt @@ -0,0 +1,21 @@ +package ai.hanzo.api.core.http + +import ai.hanzo.api.core.closeWhenPhantomReachable +import java.util.stream.Stream + +/** + * A delegating wrapper around a `StreamResponse` that closes it once it's only phantom reachable. + * + * This class ensures the `StreamResponse` is closed even if the user forgets to close it. + */ +internal class PhantomReachableClosingStreamResponse( + private val streamResponse: StreamResponse +) : StreamResponse { + init { + closeWhenPhantomReachable(this, streamResponse) + } + + override fun stream(): Stream = streamResponse.stream() + + override fun close() = streamResponse.close() +} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/QueryParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/QueryParams.kt index e788ffd5..a7b8d832 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/QueryParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/QueryParams.kt @@ -2,6 +2,14 @@ package ai.hanzo.api.core.http +import ai.hanzo.api.core.JsonArray +import ai.hanzo.api.core.JsonBoolean +import ai.hanzo.api.core.JsonMissing +import ai.hanzo.api.core.JsonNull +import ai.hanzo.api.core.JsonNumber +import ai.hanzo.api.core.JsonObject +import ai.hanzo.api.core.JsonString +import ai.hanzo.api.core.JsonValue import ai.hanzo.api.core.toImmutable class QueryParams @@ -28,6 +36,39 @@ private constructor( private val map: MutableMap> = mutableMapOf() private var size: Int = 0 + fun put(key: String, value: JsonValue): Builder = apply { + when (value) { + is JsonMissing, + is JsonNull -> {} + is JsonBoolean -> put(key, value.value.toString()) + is JsonNumber -> put(key, value.value.toString()) + is JsonString -> put(key, value.value) + is JsonArray -> + put( + key, + value.values + .asSequence() + .mapNotNull { + when (it) { + is JsonMissing, + is JsonNull -> null + is JsonBoolean -> it.value.toString() + is JsonNumber -> it.value.toString() + is JsonString -> it.value + is JsonArray, + is JsonObject -> + throw IllegalArgumentException( + "Cannot comma separate non-primitives in query params" + ) + } + } + .joinToString(","), + ) + is JsonObject -> + value.values.forEach { (nestedKey, value) -> put("$key[$nestedKey]", value) } + } + } + fun put(key: String, value: String) = apply { map.getOrPut(key) { mutableListOf() }.add(value) size++ diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/RetryingHttpClient.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/RetryingHttpClient.kt index 8c020af5..e17cec71 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/RetryingHttpClient.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/RetryingHttpClient.kt @@ -1,8 +1,11 @@ package ai.hanzo.api.core.http +import ai.hanzo.api.core.DefaultSleeper import ai.hanzo.api.core.RequestOptions +import ai.hanzo.api.core.Sleeper import ai.hanzo.api.core.checkRequired import ai.hanzo.api.errors.HanzoIoException +import ai.hanzo.api.errors.HanzoRetryableException import java.io.IOException import java.time.Clock import java.time.Duration @@ -10,8 +13,6 @@ import java.time.OffsetDateTime import java.time.format.DateTimeFormatter import java.time.format.DateTimeParseException import java.time.temporal.ChronoUnit -import java.util.Timer -import java.util.TimerTask import java.util.UUID import java.util.concurrent.CompletableFuture import java.util.concurrent.ThreadLocalRandom @@ -23,16 +24,13 @@ import kotlin.math.pow class RetryingHttpClient private constructor( private val httpClient: HttpClient, + private val sleeper: Sleeper, private val clock: Clock, private val maxRetries: Int, private val idempotencyHeader: String?, ) : HttpClient { override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse { - if (!isRetryable(request) || maxRetries <= 0) { - return httpClient.execute(request, requestOptions) - } - var modifiedRequest = maybeAddIdempotencyHeader(request) // Don't send the current retry count in the headers if the caller set their own value. @@ -46,6 +44,10 @@ private constructor( modifiedRequest = setRetryCountHeader(modifiedRequest, retries) } + if (!isRetryable(modifiedRequest)) { + return httpClient.execute(modifiedRequest, requestOptions) + } + val response = try { val response = httpClient.execute(modifiedRequest, requestOptions) @@ -62,10 +64,10 @@ private constructor( null } - val backoffMillis = getRetryBackoffMillis(retries, response) + val backoffDuration = getRetryBackoffDuration(retries, response) // All responses must be closed, so close the failed one before retrying. response?.close() - Thread.sleep(backoffMillis.toMillis()) + sleeper.sleep(backoffDuration) } } @@ -73,10 +75,6 @@ private constructor( request: HttpRequest, requestOptions: RequestOptions, ): CompletableFuture { - if (!isRetryable(request) || maxRetries <= 0) { - return httpClient.executeAsync(request, requestOptions) - } - val modifiedRequest = maybeAddIdempotencyHeader(request) // Don't send the current retry count in the headers if the caller set their own value. @@ -92,8 +90,12 @@ private constructor( val requestWithRetryCount = if (shouldSendRetryCount) setRetryCountHeader(request, retries) else request - return httpClient - .executeAsync(requestWithRetryCount, requestOptions) + val responseFuture = httpClient.executeAsync(requestWithRetryCount, requestOptions) + if (!isRetryable(requestWithRetryCount)) { + return responseFuture + } + + return responseFuture .handleAsync( fun( response: HttpResponse?, @@ -111,10 +113,10 @@ private constructor( } } - val backoffMillis = getRetryBackoffMillis(retries, response) + val backoffDuration = getRetryBackoffDuration(retries, response) // All responses must be closed, so close the failed one before retrying. response?.close() - return sleepAsync(backoffMillis.toMillis()).thenCompose { + return sleeper.sleepAsync(backoffDuration).thenCompose { executeWithRetries(requestWithRetryCount, requestOptions) } } @@ -128,7 +130,10 @@ private constructor( return executeWithRetries(modifiedRequest, requestOptions) } - override fun close() = httpClient.close() + override fun close() { + httpClient.close() + sleeper.close() + } private fun isRetryable(request: HttpRequest): Boolean = // Some requests, such as when a request body is being streamed, cannot be retried because @@ -175,11 +180,12 @@ private constructor( } private fun shouldRetry(throwable: Throwable): Boolean = - // Only retry IOException and HanzoIoException, other exceptions are not intended to be - // retried. - throwable is IOException || throwable is HanzoIoException + // Only retry known retryable exceptions, other exceptions are not intended to be retried. + throwable is IOException || + throwable is HanzoIoException || + throwable is HanzoRetryableException - private fun getRetryBackoffMillis(retries: Int, response: HttpResponse?): Duration { + private fun getRetryBackoffDuration(retries: Int, response: HttpResponse?): Duration { // About the Retry-After header: // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After response @@ -226,33 +232,21 @@ private constructor( companion object { - private val TIMER = Timer("RetryingHttpClient", true) - - private fun sleepAsync(millis: Long): CompletableFuture { - val future = CompletableFuture() - TIMER.schedule( - object : TimerTask() { - override fun run() { - future.complete(null) - } - }, - millis, - ) - return future - } - @JvmStatic fun builder() = Builder() } class Builder internal constructor() { private var httpClient: HttpClient? = null + private var sleeper: Sleeper? = null private var clock: Clock = Clock.systemUTC() private var maxRetries: Int = 2 private var idempotencyHeader: String? = null fun httpClient(httpClient: HttpClient) = apply { this.httpClient = httpClient } + fun sleeper(sleeper: Sleeper) = apply { this.sleeper = sleeper } + fun clock(clock: Clock) = apply { this.clock = clock } fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } @@ -262,6 +256,7 @@ private constructor( fun build(): HttpClient = RetryingHttpClient( checkRequired("httpClient", httpClient), + sleeper ?: DefaultSleeper(), clock, maxRetries, idempotencyHeader, diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/StreamResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/StreamResponse.kt new file mode 100644 index 00000000..c3e2fb60 --- /dev/null +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/core/http/StreamResponse.kt @@ -0,0 +1,19 @@ +package ai.hanzo.api.core.http + +import java.util.stream.Stream + +interface StreamResponse : AutoCloseable { + + fun stream(): Stream + + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ + override fun close() +} + +@JvmSynthetic +internal fun StreamResponse.map(transform: (T) -> R): StreamResponse = + object : StreamResponse { + override fun stream(): Stream = this@map.stream().map(transform) + + override fun close() = this@map.close() + } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/errors/HanzoRetryableException.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/errors/HanzoRetryableException.kt new file mode 100644 index 00000000..2b70e060 --- /dev/null +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/errors/HanzoRetryableException.kt @@ -0,0 +1,14 @@ +package ai.hanzo.api.errors + +/** + * Exception that indicates a transient error that can be retried. + * + * When this exception is thrown during an HTTP request, the SDK will automatically retry the + * request up to the maximum number of retries. + * + * @param message A descriptive error message + * @param cause The underlying cause of this exception, if any + */ +class HanzoRetryableException +@JvmOverloads +constructor(message: String? = null, cause: Throwable? = null) : HanzoException(message, cause) diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/ClientGetHomeParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/ClientGetHomeParams.kt index 5e07583f..29954e1b 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/ClientGetHomeParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/ClientGetHomeParams.kt @@ -14,8 +14,10 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -156,10 +158,12 @@ private constructor( return true } - return /* spotless:off */ other is ClientGetHomeParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is ClientGetHomeParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(additionalHeaders, additionalQueryParams) override fun toString() = "ClientGetHomeParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/ClientGetHomeResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/ClientGetHomeResponse.kt index e2bca59d..558b592e 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/ClientGetHomeResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/ClientGetHomeResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class ClientGetHomeResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap = ipAddress._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -174,7 +176,7 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): IpAddress = ipAddress + fun _body(): IpAddress = ipAddress override fun _headers(): Headers = additionalHeaders @@ -185,10 +187,13 @@ private constructor( return true } - return /* spotless:off */ other is AddAddAllowedIpParams && ipAddress == other.ipAddress && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is AddAddAllowedIpParams && + ipAddress == other.ipAddress && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(ipAddress, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(ipAddress, additionalHeaders, additionalQueryParams) override fun toString() = "AddAddAllowedIpParams{ipAddress=$ipAddress, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/add/AddAddAllowedIpResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/add/AddAddAllowedIpResponse.kt index af4a57bd..8ebd313b 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/add/AddAddAllowedIpResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/add/AddAddAllowedIpResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.add import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AddAddAllowedIpResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, private val additionalProperties: MutableMap, @@ -132,17 +133,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (ip.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is IpAddress && ip == other.ip && additionalProperties == other.additionalProperties /* spotless:on */ + return other is IpAddress && + ip == other.ip && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(ip, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicCreateParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicCreateParams.kt index 4bcbcd47..1a355f7d 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicCreateParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicCreateParams.kt @@ -4,42 +4,40 @@ package ai.hanzo.api.models.anthropic import ai.hanzo.api.core.JsonValue import ai.hanzo.api.core.Params -import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.http.Headers import ai.hanzo.api.core.http.QueryParams import ai.hanzo.api.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -/** [Docs](https://docs.hanzo.ai/docs/anthropic_completion) */ +/** [Docs](https://docs.litellm.ai/docs/pass_through/anthropic_completion) */ class AnthropicCreateParams private constructor( - private val endpoint: String, + private val endpoint: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, private val additionalBodyProperties: Map, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AnthropicCreateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AnthropicCreateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AnthropicCreateParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = anthropicCreateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [AnthropicCreateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AnthropicCreateParams = AnthropicCreateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is AnthropicCreateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AnthropicCreateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AnthropicCreateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicCreateResponse.kt index ceba8bfb..a0d79f17 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.anthropic import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AnthropicCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AnthropicDeleteParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AnthropicDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AnthropicDeleteParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = anthropicDeleteParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [AnthropicDeleteParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AnthropicDeleteParams = AnthropicDeleteParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is AnthropicDeleteParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AnthropicDeleteParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AnthropicDeleteParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicDeleteResponse.kt index 6397d237..0f26ba7d 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.anthropic import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AnthropicDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AnthropicModifyParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AnthropicModifyParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AnthropicModifyParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = anthropicModifyParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [AnthropicModifyParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AnthropicModifyParams = AnthropicModifyParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is AnthropicModifyParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AnthropicModifyParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AnthropicModifyParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicModifyResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicModifyResponse.kt index efc93de3..a3e6e48f 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicModifyResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicModifyResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.anthropic import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AnthropicModifyResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(endpoint) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AnthropicRetrieveParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AnthropicRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AnthropicRetrieveParams]. */ @JvmStatic fun builder() = Builder() } @@ -51,7 +49,10 @@ private constructor( additionalQueryParams = anthropicRetrieveParams.additionalQueryParams.toBuilder() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -155,17 +156,10 @@ private constructor( * Returns an immutable instance of [AnthropicRetrieveParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AnthropicRetrieveParams = AnthropicRetrieveParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -173,7 +167,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -186,10 +180,13 @@ private constructor( return true } - return /* spotless:off */ other is AnthropicRetrieveParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is AnthropicRetrieveParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(endpoint, additionalHeaders, additionalQueryParams) override fun toString() = "AnthropicRetrieveParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicRetrieveResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicRetrieveResponse.kt index 59573bad..2e469e2a 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicRetrieveResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicRetrieveResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.anthropic import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AnthropicRetrieveResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AnthropicUpdateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AnthropicUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AnthropicUpdateParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = anthropicUpdateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [AnthropicUpdateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AnthropicUpdateParams = AnthropicUpdateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is AnthropicUpdateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AnthropicUpdateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AnthropicUpdateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicUpdateResponse.kt index 7462c265..6ae9883f 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/anthropic/AnthropicUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.anthropic import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AnthropicUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AssemblyaiCreateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AssemblyaiCreateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AssemblyaiCreateParams]. */ @JvmStatic fun builder() = Builder() } @@ -60,7 +58,10 @@ private constructor( assemblyaiCreateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -186,30 +187,22 @@ private constructor( * Returns an immutable instance of [AssemblyaiCreateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AssemblyaiCreateParams = AssemblyaiCreateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -222,10 +215,15 @@ private constructor( return true } - return /* spotless:off */ other is AssemblyaiCreateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AssemblyaiCreateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AssemblyaiCreateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiCreateResponse.kt index 3ce2eb79..1bc70c35 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.assemblyai import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AssemblyaiCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AssemblyaiDeleteParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AssemblyaiDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AssemblyaiDeleteParams]. */ @JvmStatic fun builder() = Builder() } @@ -60,7 +58,10 @@ private constructor( assemblyaiDeleteParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -186,30 +187,22 @@ private constructor( * Returns an immutable instance of [AssemblyaiDeleteParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AssemblyaiDeleteParams = AssemblyaiDeleteParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -222,10 +215,15 @@ private constructor( return true } - return /* spotless:off */ other is AssemblyaiDeleteParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AssemblyaiDeleteParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AssemblyaiDeleteParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiDeleteResponse.kt index de8d7e0d..fd1fc9f7 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.assemblyai import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AssemblyaiDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AssemblyaiPatchParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AssemblyaiPatchParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AssemblyaiPatchParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = assemblyaiPatchParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [AssemblyaiPatchParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AssemblyaiPatchParams = AssemblyaiPatchParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is AssemblyaiPatchParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AssemblyaiPatchParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AssemblyaiPatchParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiPatchResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiPatchResponse.kt index 9302c4e5..dd0a2b2b 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiPatchResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiPatchResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.assemblyai import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AssemblyaiPatchResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(endpoint) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AssemblyaiRetrieveParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AssemblyaiRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AssemblyaiRetrieveParams]. */ @JvmStatic fun builder() = Builder() } @@ -51,7 +49,10 @@ private constructor( additionalQueryParams = assemblyaiRetrieveParams.additionalQueryParams.toBuilder() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -155,17 +156,10 @@ private constructor( * Returns an immutable instance of [AssemblyaiRetrieveParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AssemblyaiRetrieveParams = AssemblyaiRetrieveParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -173,7 +167,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -186,10 +180,13 @@ private constructor( return true } - return /* spotless:off */ other is AssemblyaiRetrieveParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is AssemblyaiRetrieveParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(endpoint, additionalHeaders, additionalQueryParams) override fun toString() = "AssemblyaiRetrieveParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiRetrieveResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiRetrieveResponse.kt index 528d5425..0f74b199 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiRetrieveResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiRetrieveResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.assemblyai import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AssemblyaiRetrieveResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AssemblyaiUpdateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AssemblyaiUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AssemblyaiUpdateParams]. */ @JvmStatic fun builder() = Builder() } @@ -60,7 +58,10 @@ private constructor( assemblyaiUpdateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -186,30 +187,22 @@ private constructor( * Returns an immutable instance of [AssemblyaiUpdateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AssemblyaiUpdateParams = AssemblyaiUpdateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -222,10 +215,15 @@ private constructor( return true } - return /* spotless:off */ other is AssemblyaiUpdateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AssemblyaiUpdateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AssemblyaiUpdateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiUpdateResponse.kt index fa31921e..9f670742 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assemblyai/AssemblyaiUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.assemblyai import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AssemblyaiUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -185,8 +188,7 @@ private constructor( ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) override fun _headers(): Headers = additionalHeaders @@ -198,10 +200,14 @@ private constructor( return true } - return /* spotless:off */ other is AssistantCreateParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AssistantCreateParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AssistantCreateParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assistants/AssistantCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assistants/AssistantCreateResponse.kt index fb1b557f..1bca8a8d 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assistants/AssistantCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assistants/AssistantCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.assistants import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AssistantCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun assistantId(): String = assistantId + fun assistantId(): Optional = Optional.ofNullable(assistantId) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AssistantDeleteParams]. - * - * The following fields are required: - * ```java - * .assistantId() - * ``` - */ + @JvmStatic fun none(): AssistantDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AssistantDeleteParams]. */ @JvmStatic fun builder() = Builder() } @@ -63,7 +61,10 @@ private constructor( additionalBodyProperties = assistantDeleteParams.additionalBodyProperties.toMutableMap() } - fun assistantId(assistantId: String) = apply { this.assistantId = assistantId } + fun assistantId(assistantId: String?) = apply { this.assistantId = assistantId } + + /** Alias for calling [Builder.assistantId] with `assistantId.orElse(null)`. */ + fun assistantId(assistantId: Optional) = assistantId(assistantId.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -189,30 +190,22 @@ private constructor( * Returns an immutable instance of [AssistantDeleteParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .assistantId() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AssistantDeleteParams = AssistantDeleteParams( - checkRequired("assistantId", assistantId), + assistantId, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> assistantId + 0 -> assistantId ?: "" else -> "" } @@ -225,10 +218,20 @@ private constructor( return true } - return /* spotless:off */ other is AssistantDeleteParams && assistantId == other.assistantId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AssistantDeleteParams && + assistantId == other.assistantId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(assistantId, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + assistantId, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) override fun toString() = "AssistantDeleteParams{assistantId=$assistantId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assistants/AssistantDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assistants/AssistantDeleteResponse.kt index f83f2039..b2712591 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assistants/AssistantDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/assistants/AssistantDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.assistants import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AssistantDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -185,8 +188,7 @@ private constructor( ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) override fun _headers(): Headers = additionalHeaders @@ -198,10 +200,14 @@ private constructor( return true } - return /* spotless:off */ other is SpeechCreateParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is SpeechCreateParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "SpeechCreateParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/audio/speech/SpeechCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/audio/speech/SpeechCreateResponse.kt index 25e912b9..463c5776 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/audio/speech/SpeechCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/audio/speech/SpeechCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.audio.speech import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class SpeechCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = body._file() + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -75,6 +83,15 @@ private constructor( additionalQueryParams = transcriptionCreateParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [file] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun file(file: InputStream) = apply { body.file(file) } /** @@ -88,7 +105,26 @@ private constructor( fun file(file: ByteArray) = apply { body.file(file) } - fun file(file: Path) = apply { body.file(file) } + fun file(path: Path) = apply { body.file(path) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -208,14 +244,20 @@ private constructor( ) } - @JvmSynthetic - internal fun _body(): Map> = mapOf("file" to _file()).toImmutable() + fun _body(): Map> = + (mapOf("file" to _file()) + + _additionalBodyProperties().mapValues { (_, value) -> MultipartField.of(value) }) + .toImmutable() override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams - class Body private constructor(private val file: MultipartField) { + class Body + private constructor( + private val file: MultipartField, + private val additionalProperties: MutableMap, + ) { /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is @@ -230,6 +272,16 @@ private constructor( */ @JsonProperty("file") @ExcludeMissing fun _file(): MultipartField = file + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + fun toBuilder() = Builder().from(this) companion object { @@ -249,8 +301,13 @@ private constructor( class Builder internal constructor() { private var file: MultipartField? = null + private var additionalProperties: MutableMap = mutableMapOf() - @JvmSynthetic internal fun from(body: Body) = apply { file = body.file } + @JvmSynthetic + internal fun from(body: Body) = apply { + file = body.file + additionalProperties = body.additionalProperties.toMutableMap() + } fun file(file: InputStream) = file(MultipartField.of(file)) @@ -265,14 +322,33 @@ private constructor( fun file(file: ByteArray) = file(file.inputStream()) - fun file(file: Path) = + fun file(path: Path) = file( MultipartField.builder() - .value(file.inputStream()) - .filename(file.name) + .value(path.inputStream()) + .filename(path.name) .build() ) + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + /** * Returns an immutable instance of [Body]. * @@ -285,7 +361,8 @@ private constructor( * * @throws IllegalStateException if any required field is unset. */ - fun build(): Body = Body(checkRequired("file", file)) + fun build(): Body = + Body(checkRequired("file", file), additionalProperties.toMutableMap()) } private var validated: Boolean = false @@ -299,21 +376,29 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && file == other.file /* spotless:on */ + return other is Body && + file == other.file && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(file) } - /* spotless:on */ + private val hashCode: Int by lazy { Objects.hash(file, additionalProperties) } override fun hashCode(): Int = hashCode - override fun toString() = "Body{file=$file}" + override fun toString() = "Body{file=$file, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { @@ -321,10 +406,13 @@ private constructor( return true } - return /* spotless:off */ other is TranscriptionCreateParams && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is TranscriptionCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) override fun toString() = "TranscriptionCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/audio/transcriptions/TranscriptionCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/audio/transcriptions/TranscriptionCreateResponse.kt index ade45396..224698c6 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/audio/transcriptions/TranscriptionCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/audio/transcriptions/TranscriptionCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.audio.transcriptions import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class TranscriptionCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(endpoint) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AzureCallParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AzureCallParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AzureCallParams]. */ @JvmStatic fun builder() = Builder() } @@ -55,7 +56,10 @@ private constructor( additionalQueryParams = azureCallParams.additionalQueryParams.toBuilder() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -159,25 +163,14 @@ private constructor( * Returns an immutable instance of [AzureCallParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AzureCallParams = - AzureCallParams( - checkRequired("endpoint", endpoint), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + AzureCallParams(endpoint, additionalHeaders.build(), additionalQueryParams.build()) } fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -190,10 +183,13 @@ private constructor( return true } - return /* spotless:off */ other is AzureCallParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is AzureCallParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(endpoint, additionalHeaders, additionalQueryParams) override fun toString() = "AzureCallParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureCallResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureCallResponse.kt index 3cc960b9..c09a388b 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureCallResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureCallResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.azure import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AzureCallResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AzureCreateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AzureCreateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AzureCreateParams]. */ @JvmStatic fun builder() = Builder() } @@ -63,7 +64,10 @@ private constructor( additionalBodyProperties = azureCreateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -189,30 +193,22 @@ private constructor( * Returns an immutable instance of [AzureCreateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AzureCreateParams = AzureCreateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -225,10 +221,15 @@ private constructor( return true } - return /* spotless:off */ other is AzureCreateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AzureCreateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AzureCreateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureCreateResponse.kt index 0fc90f78..b790db61 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.azure import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AzureCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AzureDeleteParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AzureDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AzureDeleteParams]. */ @JvmStatic fun builder() = Builder() } @@ -63,7 +64,10 @@ private constructor( additionalBodyProperties = azureDeleteParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -189,30 +193,22 @@ private constructor( * Returns an immutable instance of [AzureDeleteParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AzureDeleteParams = AzureDeleteParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -225,10 +221,15 @@ private constructor( return true } - return /* spotless:off */ other is AzureDeleteParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AzureDeleteParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AzureDeleteParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureDeleteResponse.kt index 4a7d1908..fc429a8c 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.azure import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AzureDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AzurePatchParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AzurePatchParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AzurePatchParams]. */ @JvmStatic fun builder() = Builder() } @@ -63,7 +64,10 @@ private constructor( additionalBodyProperties = azurePatchParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -189,30 +193,22 @@ private constructor( * Returns an immutable instance of [AzurePatchParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AzurePatchParams = AzurePatchParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -225,10 +221,15 @@ private constructor( return true } - return /* spotless:off */ other is AzurePatchParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AzurePatchParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AzurePatchParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzurePatchResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzurePatchResponse.kt index 2c1e6167..abd70a20 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzurePatchResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzurePatchResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.azure import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AzurePatchResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [AzureUpdateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): AzureUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AzureUpdateParams]. */ @JvmStatic fun builder() = Builder() } @@ -63,7 +64,10 @@ private constructor( additionalBodyProperties = azureUpdateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -189,30 +193,22 @@ private constructor( * Returns an immutable instance of [AzureUpdateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): AzureUpdateParams = AzureUpdateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -225,10 +221,15 @@ private constructor( return true } - return /* spotless:off */ other is AzureUpdateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AzureUpdateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "AzureUpdateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureUpdateResponse.kt index 39756b08..1eb7ecdc 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/azure/AzureUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.azure import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class AzureUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, @@ -35,12 +36,15 @@ private constructor( fun provider(): String = provider - fun batchId(): String = batchId + fun batchId(): Optional = Optional.ofNullable(batchId) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -54,7 +58,6 @@ private constructor( * The following fields are required: * ```java * .provider() - * .batchId() * ``` */ @JvmStatic fun builder() = Builder() @@ -81,7 +84,10 @@ private constructor( fun provider(provider: String) = apply { this.provider = provider } - fun batchId(batchId: String) = apply { this.batchId = batchId } + fun batchId(batchId: String?) = apply { this.batchId = batchId } + + /** Alias for calling [Builder.batchId] with `batchId.orElse(null)`. */ + fun batchId(batchId: Optional) = batchId(batchId.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -211,7 +217,6 @@ private constructor( * The following fields are required: * ```java * .provider() - * .batchId() * ``` * * @throws IllegalStateException if any required field is unset. @@ -219,21 +224,20 @@ private constructor( fun build(): BatchCancelWithProviderParams = BatchCancelWithProviderParams( checkRequired("provider", provider), - checkRequired("batchId", batchId), + batchId, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { 0 -> provider - 1 -> batchId + 1 -> batchId ?: "" else -> "" } @@ -246,10 +250,22 @@ private constructor( return true } - return /* spotless:off */ other is BatchCancelWithProviderParams && provider == other.provider && batchId == other.batchId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is BatchCancelWithProviderParams && + provider == other.provider && + batchId == other.batchId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(provider, batchId, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + provider, + batchId, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) override fun toString() = "BatchCancelWithProviderParams{provider=$provider, batchId=$batchId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCancelWithProviderResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCancelWithProviderResponse.kt index 8b4bce9c..5611e674 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCancelWithProviderResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCancelWithProviderResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.batches import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BatchCancelWithProviderResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -86,17 +88,31 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(provider) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -207,8 +210,7 @@ private constructor( ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) override fun _headers(): Headers = additionalHeaders @@ -226,10 +228,15 @@ private constructor( return true } - return /* spotless:off */ other is BatchCreateParams && provider == other.provider && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is BatchCreateParams && + provider == other.provider && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(provider, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(provider, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "BatchCreateParams{provider=$provider, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCreateResponse.kt index 873b9a9d..c8334335 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.batches import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BatchCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun provider(): String = provider + fun provider(): Optional = Optional.ofNullable(provider) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): BatchCreateWithProviderParams = builder().build() + /** * Returns a mutable builder for constructing an instance of * [BatchCreateWithProviderParams]. - * - * The following fields are required: - * ```java - * .provider() - * ``` */ @JvmStatic fun builder() = Builder() } @@ -75,7 +75,10 @@ private constructor( batchCreateWithProviderParams.additionalBodyProperties.toMutableMap() } - fun provider(provider: String) = apply { this.provider = provider } + fun provider(provider: String?) = apply { this.provider = provider } + + /** Alias for calling [Builder.provider] with `provider.orElse(null)`. */ + fun provider(provider: Optional) = provider(provider.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -201,30 +204,22 @@ private constructor( * Returns an immutable instance of [BatchCreateWithProviderParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .provider() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): BatchCreateWithProviderParams = BatchCreateWithProviderParams( - checkRequired("provider", provider), + provider, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> provider + 0 -> provider ?: "" else -> "" } @@ -237,10 +232,15 @@ private constructor( return true } - return /* spotless:off */ other is BatchCreateWithProviderParams && provider == other.provider && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is BatchCreateWithProviderParams && + provider == other.provider && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(provider, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(provider, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "BatchCreateWithProviderParams{provider=$provider, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCreateWithProviderResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCreateWithProviderResponse.kt index 515e2a89..b3af961d 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCreateWithProviderResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchCreateWithProviderResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.batches import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BatchCreateWithProviderResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -86,17 +88,31 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(provider) + fun targetModelNames(): Optional = Optional.ofNullable(targetModelNames) + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -54,6 +59,7 @@ private constructor( private var after: String? = null private var limit: Long? = null private var provider: String? = null + private var targetModelNames: String? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @@ -62,6 +68,7 @@ private constructor( after = batchListParams.after limit = batchListParams.limit provider = batchListParams.provider + targetModelNames = batchListParams.targetModelNames additionalHeaders = batchListParams.additionalHeaders.toBuilder() additionalQueryParams = batchListParams.additionalQueryParams.toBuilder() } @@ -88,6 +95,14 @@ private constructor( /** Alias for calling [Builder.provider] with `provider.orElse(null)`. */ fun provider(provider: Optional) = provider(provider.getOrNull()) + fun targetModelNames(targetModelNames: String?) = apply { + this.targetModelNames = targetModelNames + } + + /** Alias for calling [Builder.targetModelNames] with `targetModelNames.orElse(null)`. */ + fun targetModelNames(targetModelNames: Optional) = + targetModelNames(targetModelNames.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() putAllAdditionalHeaders(additionalHeaders) @@ -196,6 +211,7 @@ private constructor( after, limit, provider, + targetModelNames, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -209,6 +225,7 @@ private constructor( after?.let { put("after", it) } limit?.let { put("limit", it.toString()) } provider?.let { put("provider", it) } + targetModelNames?.let { put("target_model_names", it) } putAll(additionalQueryParams) } .build() @@ -218,11 +235,25 @@ private constructor( return true } - return /* spotless:off */ other is BatchListParams && after == other.after && limit == other.limit && provider == other.provider && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is BatchListParams && + after == other.after && + limit == other.limit && + provider == other.provider && + targetModelNames == other.targetModelNames && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(after, limit, provider, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + after, + limit, + provider, + targetModelNames, + additionalHeaders, + additionalQueryParams, + ) override fun toString() = - "BatchListParams{after=$after, limit=$limit, provider=$provider, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "BatchListParams{after=$after, limit=$limit, provider=$provider, targetModelNames=$targetModelNames, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchListResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchListResponse.kt index 2406ff8f..495f4a5b 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchListResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchListResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.batches import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BatchListResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(provider) fun after(): Optional = Optional.ofNullable(after) fun limit(): Optional = Optional.ofNullable(limit) + fun targetModelNames(): Optional = Optional.ofNullable(targetModelNames) + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): BatchListWithProviderParams = builder().build() + /** * Returns a mutable builder for constructing an instance of [BatchListWithProviderParams]. - * - * The following fields are required: - * ```java - * .provider() - * ``` */ @JvmStatic fun builder() = Builder() } @@ -60,6 +61,7 @@ private constructor( private var provider: String? = null private var after: String? = null private var limit: Long? = null + private var targetModelNames: String? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @@ -68,11 +70,15 @@ private constructor( provider = batchListWithProviderParams.provider after = batchListWithProviderParams.after limit = batchListWithProviderParams.limit + targetModelNames = batchListWithProviderParams.targetModelNames additionalHeaders = batchListWithProviderParams.additionalHeaders.toBuilder() additionalQueryParams = batchListWithProviderParams.additionalQueryParams.toBuilder() } - fun provider(provider: String) = apply { this.provider = provider } + fun provider(provider: String?) = apply { this.provider = provider } + + /** Alias for calling [Builder.provider] with `provider.orElse(null)`. */ + fun provider(provider: Optional) = provider(provider.getOrNull()) fun after(after: String?) = apply { this.after = after } @@ -91,6 +97,14 @@ private constructor( /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ fun limit(limit: Optional) = limit(limit.getOrNull()) + fun targetModelNames(targetModelNames: String?) = apply { + this.targetModelNames = targetModelNames + } + + /** Alias for calling [Builder.targetModelNames] with `targetModelNames.orElse(null)`. */ + fun targetModelNames(targetModelNames: Optional) = + targetModelNames(targetModelNames.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() putAllAdditionalHeaders(additionalHeaders) @@ -193,19 +207,13 @@ private constructor( * Returns an immutable instance of [BatchListWithProviderParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .provider() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): BatchListWithProviderParams = BatchListWithProviderParams( - checkRequired("provider", provider), + provider, after, limit, + targetModelNames, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -213,7 +221,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { - 0 -> provider + 0 -> provider ?: "" else -> "" } @@ -224,6 +232,7 @@ private constructor( .apply { after?.let { put("after", it) } limit?.let { put("limit", it.toString()) } + targetModelNames?.let { put("target_model_names", it) } putAll(additionalQueryParams) } .build() @@ -233,11 +242,25 @@ private constructor( return true } - return /* spotless:off */ other is BatchListWithProviderParams && provider == other.provider && after == other.after && limit == other.limit && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is BatchListWithProviderParams && + provider == other.provider && + after == other.after && + limit == other.limit && + targetModelNames == other.targetModelNames && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(provider, after, limit, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + provider, + after, + limit, + targetModelNames, + additionalHeaders, + additionalQueryParams, + ) override fun toString() = - "BatchListWithProviderParams{provider=$provider, after=$after, limit=$limit, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "BatchListWithProviderParams{provider=$provider, after=$after, limit=$limit, targetModelNames=$targetModelNames, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchListWithProviderResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchListWithProviderResponse.kt index a5d4e878..163a8fe4 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchListWithProviderResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchListWithProviderResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.batches import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BatchListWithProviderResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -84,17 +86,31 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(batchId) fun provider(): Optional = Optional.ofNullable(provider) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [BatchRetrieveParams]. - * - * The following fields are required: - * ```java - * .batchId() - * ``` - */ + @JvmStatic fun none(): BatchRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [BatchRetrieveParams]. */ @JvmStatic fun builder() = Builder() } @@ -69,7 +65,10 @@ private constructor( } /** The ID of the batch to retrieve */ - fun batchId(batchId: String) = apply { this.batchId = batchId } + fun batchId(batchId: String?) = apply { this.batchId = batchId } + + /** Alias for calling [Builder.batchId] with `batchId.orElse(null)`. */ + fun batchId(batchId: Optional) = batchId(batchId.getOrNull()) fun provider(provider: String?) = apply { this.provider = provider } @@ -178,17 +177,10 @@ private constructor( * Returns an immutable instance of [BatchRetrieveParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .batchId() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): BatchRetrieveParams = BatchRetrieveParams( - checkRequired("batchId", batchId), + batchId, provider, additionalHeaders.build(), additionalQueryParams.build(), @@ -197,7 +189,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { - 0 -> batchId + 0 -> batchId ?: "" else -> "" } @@ -216,10 +208,15 @@ private constructor( return true } - return /* spotless:off */ other is BatchRetrieveParams && batchId == other.batchId && provider == other.provider && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is BatchRetrieveParams && + batchId == other.batchId && + provider == other.provider && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(batchId, provider, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(batchId, provider, additionalHeaders, additionalQueryParams) override fun toString() = "BatchRetrieveParams{batchId=$batchId, provider=$provider, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchRetrieveResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchRetrieveResponse.kt index 04934d68..21af2aa0 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchRetrieveResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchRetrieveResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.batches import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BatchRetrieveResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(batchId) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -46,7 +50,6 @@ private constructor( * The following fields are required: * ```java * .provider() - * .batchId() * ``` */ @JvmStatic fun builder() = Builder() @@ -73,7 +76,10 @@ private constructor( fun provider(provider: String) = apply { this.provider = provider } /** The ID of the batch to retrieve */ - fun batchId(batchId: String) = apply { this.batchId = batchId } + fun batchId(batchId: String?) = apply { this.batchId = batchId } + + /** Alias for calling [Builder.batchId] with `batchId.orElse(null)`. */ + fun batchId(batchId: Optional) = batchId(batchId.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -181,7 +187,6 @@ private constructor( * The following fields are required: * ```java * .provider() - * .batchId() * ``` * * @throws IllegalStateException if any required field is unset. @@ -189,7 +194,7 @@ private constructor( fun build(): BatchRetrieveWithProviderParams = BatchRetrieveWithProviderParams( checkRequired("provider", provider), - checkRequired("batchId", batchId), + batchId, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -198,7 +203,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { 0 -> provider - 1 -> batchId + 1 -> batchId ?: "" else -> "" } @@ -211,10 +216,15 @@ private constructor( return true } - return /* spotless:off */ other is BatchRetrieveWithProviderParams && provider == other.provider && batchId == other.batchId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is BatchRetrieveWithProviderParams && + provider == other.provider && + batchId == other.batchId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(provider, batchId, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(provider, batchId, additionalHeaders, additionalQueryParams) override fun toString() = "BatchRetrieveWithProviderParams{provider=$provider, batchId=$batchId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchRetrieveWithProviderResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchRetrieveWithProviderResponse.kt index acfa3095..92ad1347 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchRetrieveWithProviderResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/BatchRetrieveWithProviderResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.batches import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BatchRetrieveWithProviderResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -86,17 +88,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun batchId(): String = batchId + fun batchId(): Optional = Optional.ofNullable(batchId) fun provider(): Optional = Optional.ofNullable(provider) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [CancelCancelParams]. - * - * The following fields are required: - * ```java - * .batchId() - * ``` - */ + @JvmStatic fun none(): CancelCancelParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [CancelCancelParams]. */ @JvmStatic fun builder() = Builder() } @@ -77,7 +74,10 @@ private constructor( additionalBodyProperties = cancelCancelParams.additionalBodyProperties.toMutableMap() } - fun batchId(batchId: String) = apply { this.batchId = batchId } + fun batchId(batchId: String?) = apply { this.batchId = batchId } + + /** Alias for calling [Builder.batchId] with `batchId.orElse(null)`. */ + fun batchId(batchId: Optional) = batchId(batchId.getOrNull()) fun provider(provider: String?) = apply { this.provider = provider } @@ -208,17 +208,10 @@ private constructor( * Returns an immutable instance of [CancelCancelParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .batchId() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): CancelCancelParams = CancelCancelParams( - checkRequired("batchId", batchId), + batchId, provider, additionalHeaders.build(), additionalQueryParams.build(), @@ -226,13 +219,12 @@ private constructor( ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> batchId + 0 -> batchId ?: "" else -> "" } @@ -251,10 +243,22 @@ private constructor( return true } - return /* spotless:off */ other is CancelCancelParams && batchId == other.batchId && provider == other.provider && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is CancelCancelParams && + batchId == other.batchId && + provider == other.provider && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(batchId, provider, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + batchId, + provider, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) override fun toString() = "CancelCancelParams{batchId=$batchId, provider=$provider, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/cancel/CancelCancelResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/cancel/CancelCancelResponse.kt index 33fb3d26..e06c82c0 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/cancel/CancelCancelResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/batches/cancel/CancelCancelResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.batches.cancel import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CancelCancelResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [BedrockCreateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): BedrockCreateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [BedrockCreateParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +60,10 @@ private constructor( additionalBodyProperties = bedrockCreateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +189,22 @@ private constructor( * Returns an immutable instance of [BedrockCreateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): BedrockCreateParams = BedrockCreateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +217,15 @@ private constructor( return true } - return /* spotless:off */ other is BedrockCreateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is BedrockCreateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "BedrockCreateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockCreateResponse.kt index 448ce7cd..39d0b75d 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.bedrock import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BedrockCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [BedrockDeleteParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): BedrockDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [BedrockDeleteParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +60,10 @@ private constructor( additionalBodyProperties = bedrockDeleteParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +189,22 @@ private constructor( * Returns an immutable instance of [BedrockDeleteParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): BedrockDeleteParams = BedrockDeleteParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +217,15 @@ private constructor( return true } - return /* spotless:off */ other is BedrockDeleteParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is BedrockDeleteParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "BedrockDeleteParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockDeleteResponse.kt index 2bad3fdd..fae52989 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.bedrock import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BedrockDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [BedrockPatchParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): BedrockPatchParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [BedrockPatchParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +60,10 @@ private constructor( additionalBodyProperties = bedrockPatchParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +189,22 @@ private constructor( * Returns an immutable instance of [BedrockPatchParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): BedrockPatchParams = BedrockPatchParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +217,15 @@ private constructor( return true } - return /* spotless:off */ other is BedrockPatchParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is BedrockPatchParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "BedrockPatchParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockPatchResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockPatchResponse.kt index a9820813..6f4065d3 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockPatchResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockPatchResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.bedrock import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BedrockPatchResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(endpoint) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [BedrockRetrieveParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): BedrockRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [BedrockRetrieveParams]. */ @JvmStatic fun builder() = Builder() } @@ -51,7 +52,10 @@ private constructor( additionalQueryParams = bedrockRetrieveParams.additionalQueryParams.toBuilder() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -155,17 +159,10 @@ private constructor( * Returns an immutable instance of [BedrockRetrieveParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): BedrockRetrieveParams = BedrockRetrieveParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -173,7 +170,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -186,10 +183,13 @@ private constructor( return true } - return /* spotless:off */ other is BedrockRetrieveParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is BedrockRetrieveParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(endpoint, additionalHeaders, additionalQueryParams) override fun toString() = "BedrockRetrieveParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockRetrieveResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockRetrieveResponse.kt index 3a1a57ac..98ed529b 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockRetrieveResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockRetrieveResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.bedrock import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BedrockRetrieveResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [BedrockUpdateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): BedrockUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [BedrockUpdateParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +60,10 @@ private constructor( additionalBodyProperties = bedrockUpdateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +189,22 @@ private constructor( * Returns an immutable instance of [BedrockUpdateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): BedrockUpdateParams = BedrockUpdateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +217,15 @@ private constructor( return true } - return /* spotless:off */ other is BedrockUpdateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is BedrockUpdateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "BedrockUpdateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockUpdateResponse.kt index 1b8a6547..a948a745 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/bedrock/BedrockUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.bedrock import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BedrockUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = budgetNew._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -188,7 +192,7 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): BudgetNew = budgetNew + fun _body(): BudgetNew = budgetNew override fun _headers(): Headers = additionalHeaders @@ -199,10 +203,13 @@ private constructor( return true } - return /* spotless:off */ other is BudgetCreateParams && budgetNew == other.budgetNew && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is BudgetCreateParams && + budgetNew == other.budgetNew && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(budgetNew, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(budgetNew, additionalHeaders, additionalQueryParams) override fun toString() = "BudgetCreateParams{budgetNew=$budgetNew, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetCreateResponse.kt index ff8260be..453ffc4c 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.budget import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BudgetCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = body._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -79,6 +81,15 @@ private constructor( additionalQueryParams = budgetDeleteParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [id] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun id(id: String) = apply { body.id(id) } /** @@ -226,13 +237,14 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): Body = body + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val id: JsonField, private val additionalProperties: MutableMap, @@ -349,17 +361,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (id.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && id == other.id && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Body && + id == other.id && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(id, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -371,10 +399,13 @@ private constructor( return true } - return /* spotless:off */ other is BudgetDeleteParams && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is BudgetDeleteParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) override fun toString() = "BudgetDeleteParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetDeleteResponse.kt index f4647113..e8581a83 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.budget import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BudgetDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = body._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -81,6 +84,15 @@ private constructor( additionalQueryParams = budgetInfoParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [budgets] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun budgets(budgets: List) = apply { body.budgets(budgets) } /** @@ -232,13 +244,14 @@ private constructor( BudgetInfoParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) } - @JvmSynthetic internal fun _body(): Body = body + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val budgets: JsonField>, private val additionalProperties: MutableMap, @@ -375,17 +388,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (budgets.asKnown().getOrNull()?.size ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && budgets == other.budgets && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Body && + budgets == other.budgets && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(budgets, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -398,10 +427,13 @@ private constructor( return true } - return /* spotless:off */ other is BudgetInfoParams && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is BudgetInfoParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) override fun toString() = "BudgetInfoParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetInfoResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetInfoResponse.kt index d13445c0..42bc9993 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetInfoResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetInfoResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.budget import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BudgetInfoResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, private val budgetId: JsonField, + private val budgetResetAt: JsonField, private val maxBudget: JsonField, private val maxParallelRequests: JsonField, private val modelMaxBudget: JsonField, @@ -36,6 +39,9 @@ private constructor( @ExcludeMissing budgetDuration: JsonField = JsonMissing.of(), @JsonProperty("budget_id") @ExcludeMissing budgetId: JsonField = JsonMissing.of(), + @JsonProperty("budget_reset_at") + @ExcludeMissing + budgetResetAt: JsonField = JsonMissing.of(), @JsonProperty("max_budget") @ExcludeMissing maxBudget: JsonField = JsonMissing.of(), @JsonProperty("max_parallel_requests") @ExcludeMissing @@ -51,6 +57,7 @@ private constructor( ) : this( budgetDuration, budgetId, + budgetResetAt, maxBudget, maxParallelRequests, modelMaxBudget, @@ -66,8 +73,7 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetDuration(): Optional = - Optional.ofNullable(budgetDuration.getNullable("budget_duration")) + fun budgetDuration(): Optional = budgetDuration.getOptional("budget_duration") /** * The unique budget id. @@ -75,7 +81,15 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetId(): Optional = Optional.ofNullable(budgetId.getNullable("budget_id")) + fun budgetId(): Optional = budgetId.getOptional("budget_id") + + /** + * Datetime when the budget is reset + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun budgetResetAt(): Optional = budgetResetAt.getOptional("budget_reset_at") /** * Requests will fail if this budget (in USD) is exceeded. @@ -83,7 +97,7 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun maxBudget(): Optional = Optional.ofNullable(maxBudget.getNullable("max_budget")) + fun maxBudget(): Optional = maxBudget.getOptional("max_budget") /** * Max concurrent requests allowed for this budget id. @@ -92,7 +106,7 @@ private constructor( * server responded with an unexpected value). */ fun maxParallelRequests(): Optional = - Optional.ofNullable(maxParallelRequests.getNullable("max_parallel_requests")) + maxParallelRequests.getOptional("max_parallel_requests") /** * Max budget for each model (e.g. {'gpt-4o': {'max_budget': '0.0000001', 'budget_duration': @@ -101,8 +115,7 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun modelMaxBudget(): Optional = - Optional.ofNullable(modelMaxBudget.getNullable("model_max_budget")) + fun modelMaxBudget(): Optional = modelMaxBudget.getOptional("model_max_budget") /** * Max requests per minute, allowed for this budget id. @@ -110,7 +123,7 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rpmLimit(): Optional = Optional.ofNullable(rpmLimit.getNullable("rpm_limit")) + fun rpmLimit(): Optional = rpmLimit.getOptional("rpm_limit") /** * Requests will NOT fail if this is exceeded. Will fire alerting though. @@ -118,7 +131,7 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun softBudget(): Optional = Optional.ofNullable(softBudget.getNullable("soft_budget")) + fun softBudget(): Optional = softBudget.getOptional("soft_budget") /** * Max tokens per minute, allowed for this budget id. @@ -126,7 +139,7 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tpmLimit(): Optional = Optional.ofNullable(tpmLimit.getNullable("tpm_limit")) + fun tpmLimit(): Optional = tpmLimit.getOptional("tpm_limit") /** * Returns the raw JSON value of [budgetDuration]. @@ -144,6 +157,15 @@ private constructor( */ @JsonProperty("budget_id") @ExcludeMissing fun _budgetId(): JsonField = budgetId + /** + * Returns the raw JSON value of [budgetResetAt]. + * + * Unlike [budgetResetAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("budget_reset_at") + @ExcludeMissing + fun _budgetResetAt(): JsonField = budgetResetAt + /** * Returns the raw JSON value of [maxBudget]. * @@ -214,6 +236,7 @@ private constructor( private var budgetDuration: JsonField = JsonMissing.of() private var budgetId: JsonField = JsonMissing.of() + private var budgetResetAt: JsonField = JsonMissing.of() private var maxBudget: JsonField = JsonMissing.of() private var maxParallelRequests: JsonField = JsonMissing.of() private var modelMaxBudget: JsonField = JsonMissing.of() @@ -226,6 +249,7 @@ private constructor( internal fun from(budgetNew: BudgetNew) = apply { budgetDuration = budgetNew.budgetDuration budgetId = budgetNew.budgetId + budgetResetAt = budgetNew.budgetResetAt maxBudget = budgetNew.maxBudget maxParallelRequests = budgetNew.maxParallelRequests modelMaxBudget = budgetNew.modelMaxBudget @@ -268,6 +292,25 @@ private constructor( */ fun budgetId(budgetId: JsonField) = apply { this.budgetId = budgetId } + /** Datetime when the budget is reset */ + fun budgetResetAt(budgetResetAt: OffsetDateTime?) = + budgetResetAt(JsonField.ofNullable(budgetResetAt)) + + /** Alias for calling [Builder.budgetResetAt] with `budgetResetAt.orElse(null)`. */ + fun budgetResetAt(budgetResetAt: Optional) = + budgetResetAt(budgetResetAt.getOrNull()) + + /** + * Sets [Builder.budgetResetAt] to an arbitrary JSON value. + * + * You should usually call [Builder.budgetResetAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun budgetResetAt(budgetResetAt: JsonField) = apply { + this.budgetResetAt = budgetResetAt + } + /** Requests will fail if this budget (in USD) is exceeded. */ fun maxBudget(maxBudget: Double?) = maxBudget(JsonField.ofNullable(maxBudget)) @@ -433,6 +476,7 @@ private constructor( BudgetNew( budgetDuration, budgetId, + budgetResetAt, maxBudget, maxParallelRequests, modelMaxBudget, @@ -452,6 +496,7 @@ private constructor( budgetDuration() budgetId() + budgetResetAt() maxBudget() maxParallelRequests() modelMaxBudget().ifPresent { it.validate() } @@ -461,6 +506,31 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (budgetDuration.asKnown().isPresent) 1 else 0) + + (if (budgetId.asKnown().isPresent) 1 else 0) + + (if (budgetResetAt.asKnown().isPresent) 1 else 0) + + (if (maxBudget.asKnown().isPresent) 1 else 0) + + (if (maxParallelRequests.asKnown().isPresent) 1 else 0) + + (modelMaxBudget.asKnown().getOrNull()?.validity() ?: 0) + + (if (rpmLimit.asKnown().isPresent) 1 else 0) + + (if (softBudget.asKnown().isPresent) 1 else 0) + + (if (tpmLimit.asKnown().isPresent) 1 else 0) + /** * Max budget for each model (e.g. {'gpt-4o': {'max_budget': '0.0000001', 'budget_duration': * '1d', 'tpm_limit': 1000, 'rpm_limit': 1000}}) @@ -531,17 +601,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is ModelMaxBudget && additionalProperties == other.additionalProperties /* spotless:on */ + return other is ModelMaxBudget && additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -553,15 +639,36 @@ private constructor( return true } - return /* spotless:off */ other is BudgetNew && budgetDuration == other.budgetDuration && budgetId == other.budgetId && maxBudget == other.maxBudget && maxParallelRequests == other.maxParallelRequests && modelMaxBudget == other.modelMaxBudget && rpmLimit == other.rpmLimit && softBudget == other.softBudget && tpmLimit == other.tpmLimit && additionalProperties == other.additionalProperties /* spotless:on */ + return other is BudgetNew && + budgetDuration == other.budgetDuration && + budgetId == other.budgetId && + budgetResetAt == other.budgetResetAt && + maxBudget == other.maxBudget && + maxParallelRequests == other.maxParallelRequests && + modelMaxBudget == other.modelMaxBudget && + rpmLimit == other.rpmLimit && + softBudget == other.softBudget && + tpmLimit == other.tpmLimit && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(budgetDuration, budgetId, maxBudget, maxParallelRequests, modelMaxBudget, rpmLimit, softBudget, tpmLimit, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + budgetDuration, + budgetId, + budgetResetAt, + maxBudget, + maxParallelRequests, + modelMaxBudget, + rpmLimit, + softBudget, + tpmLimit, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "BudgetNew{budgetDuration=$budgetDuration, budgetId=$budgetId, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, modelMaxBudget=$modelMaxBudget, rpmLimit=$rpmLimit, softBudget=$softBudget, tpmLimit=$tpmLimit, additionalProperties=$additionalProperties}" + "BudgetNew{budgetDuration=$budgetDuration, budgetId=$budgetId, budgetResetAt=$budgetResetAt, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, modelMaxBudget=$modelMaxBudget, rpmLimit=$rpmLimit, softBudget=$softBudget, tpmLimit=$tpmLimit, additionalProperties=$additionalProperties}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetSettingsParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetSettingsParams.kt index 6c366af2..4e77c968 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetSettingsParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetSettingsParams.kt @@ -25,8 +25,10 @@ private constructor( fun budgetId(): String = budgetId + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -193,10 +195,13 @@ private constructor( return true } - return /* spotless:off */ other is BudgetSettingsParams && budgetId == other.budgetId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is BudgetSettingsParams && + budgetId == other.budgetId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(budgetId, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(budgetId, additionalHeaders, additionalQueryParams) override fun toString() = "BudgetSettingsParams{budgetId=$budgetId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetSettingsResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetSettingsResponse.kt index b08c879e..30cb8c67 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetSettingsResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetSettingsResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.budget import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BudgetSettingsResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = budgetNew._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -188,7 +191,7 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): BudgetNew = budgetNew + fun _body(): BudgetNew = budgetNew override fun _headers(): Headers = additionalHeaders @@ -199,10 +202,13 @@ private constructor( return true } - return /* spotless:off */ other is BudgetUpdateParams && budgetNew == other.budgetNew && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is BudgetUpdateParams && + budgetNew == other.budgetNew && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(budgetNew, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(budgetNew, additionalHeaders, additionalQueryParams) override fun toString() = "BudgetUpdateParams{budgetNew=$budgetNew, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetUpdateResponse.kt index a645401e..4e1d52ab 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/budget/BudgetUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.budget import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class BudgetUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -192,8 +195,7 @@ private constructor( ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) override fun _headers(): Headers = additionalHeaders @@ -205,10 +207,14 @@ private constructor( return true } - return /* spotless:off */ other is CacheDeleteParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is CacheDeleteParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "CacheDeleteParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/CacheDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/CacheDeleteResponse.kt index 33ae5d97..68eaa853 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/CacheDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/CacheDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.cache import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CacheDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -190,8 +193,7 @@ private constructor( ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) override fun _headers(): Headers = additionalHeaders @@ -203,10 +205,14 @@ private constructor( return true } - return /* spotless:off */ other is CacheFlushAllParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is CacheFlushAllParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "CacheFlushAllParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/CacheFlushAllResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/CacheFlushAllResponse.kt index 961c97e7..e32ef1a7 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/CacheFlushAllResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/CacheFlushAllResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.cache import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CacheFlushAllResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, private val status: JsonField, - private val healthCheckCacheParams: JsonValue, - private val llmCacheParams: JsonField, + private val healthCheckCacheParams: JsonField, + private val litellmCacheParams: JsonField, private val pingResponse: JsonField, private val setCacheResponse: JsonField, private val additionalProperties: MutableMap, @@ -34,10 +36,10 @@ private constructor( @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), @JsonProperty("health_check_cache_params") @ExcludeMissing - healthCheckCacheParams: JsonValue = JsonMissing.of(), - @JsonProperty("llm_cache_params") + healthCheckCacheParams: JsonField = JsonMissing.of(), + @JsonProperty("litellm_cache_params") @ExcludeMissing - llmCacheParams: JsonField = JsonMissing.of(), + litellmCacheParams: JsonField = JsonMissing.of(), @JsonProperty("ping_response") @ExcludeMissing pingResponse: JsonField = JsonMissing.of(), @@ -48,7 +50,7 @@ private constructor( cacheType, status, healthCheckCacheParams, - llmCacheParams, + litellmCacheParams, pingResponse, setCacheResponse, mutableMapOf(), @@ -66,30 +68,31 @@ private constructor( */ fun status(): String = status.getRequired("status") - @JsonProperty("health_check_cache_params") - @ExcludeMissing - fun _healthCheckCacheParams(): JsonValue = healthCheckCacheParams + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun healthCheckCacheParams(): Optional = + healthCheckCacheParams.getOptional("health_check_cache_params") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun llmCacheParams(): Optional = - Optional.ofNullable(llmCacheParams.getNullable("llm_cache_params")) + fun litellmCacheParams(): Optional = + litellmCacheParams.getOptional("litellm_cache_params") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun pingResponse(): Optional = - Optional.ofNullable(pingResponse.getNullable("ping_response")) + fun pingResponse(): Optional = pingResponse.getOptional("ping_response") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun setCacheResponse(): Optional = - Optional.ofNullable(setCacheResponse.getNullable("set_cache_response")) + fun setCacheResponse(): Optional = setCacheResponse.getOptional("set_cache_response") /** * Returns the raw JSON value of [cacheType]. @@ -106,13 +109,24 @@ private constructor( @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status /** - * Returns the raw JSON value of [llmCacheParams]. + * Returns the raw JSON value of [healthCheckCacheParams]. * - * Unlike [llmCacheParams], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [healthCheckCacheParams], this method doesn't throw if the JSON field has an + * unexpected type. */ - @JsonProperty("llm_cache_params") + @JsonProperty("health_check_cache_params") @ExcludeMissing - fun _llmCacheParams(): JsonField = llmCacheParams + fun _healthCheckCacheParams(): JsonField = healthCheckCacheParams + + /** + * Returns the raw JSON value of [litellmCacheParams]. + * + * Unlike [litellmCacheParams], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("litellm_cache_params") + @ExcludeMissing + fun _litellmCacheParams(): JsonField = litellmCacheParams /** * Returns the raw JSON value of [pingResponse]. @@ -164,8 +178,8 @@ private constructor( private var cacheType: JsonField? = null private var status: JsonField? = null - private var healthCheckCacheParams: JsonValue = JsonMissing.of() - private var llmCacheParams: JsonField = JsonMissing.of() + private var healthCheckCacheParams: JsonField = JsonMissing.of() + private var litellmCacheParams: JsonField = JsonMissing.of() private var pingResponse: JsonField = JsonMissing.of() private var setCacheResponse: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @@ -175,7 +189,7 @@ private constructor( cacheType = cachePingResponse.cacheType status = cachePingResponse.status healthCheckCacheParams = cachePingResponse.healthCheckCacheParams - llmCacheParams = cachePingResponse.llmCacheParams + litellmCacheParams = cachePingResponse.litellmCacheParams pingResponse = cachePingResponse.pingResponse setCacheResponse = cachePingResponse.setCacheResponse additionalProperties = cachePingResponse.additionalProperties.toMutableMap() @@ -202,26 +216,46 @@ private constructor( */ fun status(status: JsonField) = apply { this.status = status } - fun healthCheckCacheParams(healthCheckCacheParams: JsonValue) = apply { - this.healthCheckCacheParams = healthCheckCacheParams - } + fun healthCheckCacheParams(healthCheckCacheParams: HealthCheckCacheParams?) = + healthCheckCacheParams(JsonField.ofNullable(healthCheckCacheParams)) - fun llmCacheParams(llmCacheParams: String?) = - llmCacheParams(JsonField.ofNullable(llmCacheParams)) + /** + * Alias for calling [Builder.healthCheckCacheParams] with + * `healthCheckCacheParams.orElse(null)`. + */ + fun healthCheckCacheParams(healthCheckCacheParams: Optional) = + healthCheckCacheParams(healthCheckCacheParams.getOrNull()) - /** Alias for calling [Builder.llmCacheParams] with `llmCacheParams.orElse(null)`. */ - fun llmCacheParams(llmCacheParams: Optional) = - llmCacheParams(llmCacheParams.getOrNull()) + /** + * Sets [Builder.healthCheckCacheParams] to an arbitrary JSON value. + * + * You should usually call [Builder.healthCheckCacheParams] with a well-typed + * [HealthCheckCacheParams] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun healthCheckCacheParams(healthCheckCacheParams: JsonField) = + apply { + this.healthCheckCacheParams = healthCheckCacheParams + } + + fun litellmCacheParams(litellmCacheParams: String?) = + litellmCacheParams(JsonField.ofNullable(litellmCacheParams)) + + /** + * Alias for calling [Builder.litellmCacheParams] with `litellmCacheParams.orElse(null)`. + */ + fun litellmCacheParams(litellmCacheParams: Optional) = + litellmCacheParams(litellmCacheParams.getOrNull()) /** - * Sets [Builder.llmCacheParams] to an arbitrary JSON value. + * Sets [Builder.litellmCacheParams] to an arbitrary JSON value. * - * You should usually call [Builder.llmCacheParams] with a well-typed [String] value + * You should usually call [Builder.litellmCacheParams] with a well-typed [String] value * instead. This method is primarily for setting the field to an undocumented or not yet * supported value. */ - fun llmCacheParams(llmCacheParams: JsonField) = apply { - this.llmCacheParams = llmCacheParams + fun litellmCacheParams(litellmCacheParams: JsonField) = apply { + this.litellmCacheParams = litellmCacheParams } fun pingResponse(pingResponse: Boolean?) = pingResponse(JsonField.ofNullable(pingResponse)) @@ -302,7 +336,7 @@ private constructor( checkRequired("cacheType", cacheType), checkRequired("status", status), healthCheckCacheParams, - llmCacheParams, + litellmCacheParams, pingResponse, setCacheResponse, additionalProperties.toMutableMap(), @@ -318,26 +352,168 @@ private constructor( cacheType() status() - llmCacheParams() + healthCheckCacheParams().ifPresent { it.validate() } + litellmCacheParams() pingResponse() setCacheResponse() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (cacheType.asKnown().isPresent) 1 else 0) + + (if (status.asKnown().isPresent) 1 else 0) + + (healthCheckCacheParams.asKnown().getOrNull()?.validity() ?: 0) + + (if (litellmCacheParams.asKnown().isPresent) 1 else 0) + + (if (pingResponse.asKnown().isPresent) 1 else 0) + + (if (setCacheResponse.asKnown().isPresent) 1 else 0) + + class HealthCheckCacheParams + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [HealthCheckCacheParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [HealthCheckCacheParams]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(healthCheckCacheParams: HealthCheckCacheParams) = apply { + additionalProperties = healthCheckCacheParams.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [HealthCheckCacheParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): HealthCheckCacheParams = + HealthCheckCacheParams(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): HealthCheckCacheParams = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is HealthCheckCacheParams && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "HealthCheckCacheParams{additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is CachePingResponse && cacheType == other.cacheType && status == other.status && healthCheckCacheParams == other.healthCheckCacheParams && llmCacheParams == other.llmCacheParams && pingResponse == other.pingResponse && setCacheResponse == other.setCacheResponse && additionalProperties == other.additionalProperties /* spotless:on */ + return other is CachePingResponse && + cacheType == other.cacheType && + status == other.status && + healthCheckCacheParams == other.healthCheckCacheParams && + litellmCacheParams == other.litellmCacheParams && + pingResponse == other.pingResponse && + setCacheResponse == other.setCacheResponse && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(cacheType, status, healthCheckCacheParams, llmCacheParams, pingResponse, setCacheResponse, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + cacheType, + status, + healthCheckCacheParams, + litellmCacheParams, + pingResponse, + setCacheResponse, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "CachePingResponse{cacheType=$cacheType, status=$status, healthCheckCacheParams=$healthCheckCacheParams, llmCacheParams=$llmCacheParams, pingResponse=$pingResponse, setCacheResponse=$setCacheResponse, additionalProperties=$additionalProperties}" + "CachePingResponse{cacheType=$cacheType, status=$status, healthCheckCacheParams=$healthCheckCacheParams, litellmCacheParams=$litellmCacheParams, pingResponse=$pingResponse, setCacheResponse=$setCacheResponse, additionalProperties=$additionalProperties}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/redis/RediRetrieveInfoParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/redis/RediRetrieveInfoParams.kt index 45fa4398..db5c54cd 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/redis/RediRetrieveInfoParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/redis/RediRetrieveInfoParams.kt @@ -14,8 +14,10 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -156,10 +158,12 @@ private constructor( return true } - return /* spotless:off */ other is RediRetrieveInfoParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is RediRetrieveInfoParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(additionalHeaders, additionalQueryParams) override fun toString() = "RediRetrieveInfoParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/redis/RediRetrieveInfoResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/redis/RediRetrieveInfoResponse.kt index 7d82b641..27c0ab55 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/redis/RediRetrieveInfoResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cache/redis/RediRetrieveInfoResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.cache.redis import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class RediRetrieveInfoResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun model(): Optional = Optional.ofNullable(model) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun messages(): List = body.messages() - fun _additionalBodyProperties(): Map = additionalBodyProperties + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun model(): String = body.model() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun caching(): Optional = body.caching() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun contextWindowFallbackDict(): Optional = + body.contextWindowFallbackDict() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fallbacks(): Optional> = body.fallbacks() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun frequencyPenalty(): Optional = body.frequencyPenalty() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functionCall(): Optional = body.functionCall() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functions(): Optional> = body.functions() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun guardrails(): Optional> = body.guardrails() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logitBias(): Optional = body.logitBias() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logprobs(): Optional = body.logprobs() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxTokens(): Optional = body.maxTokens() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = body.metadata() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun n(): Optional = body.n() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun numRetries(): Optional = body.numRetries() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun parallelToolCalls(): Optional = body.parallelToolCalls() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun presencePenalty(): Optional = body.presencePenalty() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun responseFormat(): Optional = body.responseFormat() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun seed(): Optional = body.seed() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun serviceTier(): Optional = body.serviceTier() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stop(): Optional = body.stop() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stream(): Optional = body.stream() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun streamOptions(): Optional = body.streamOptions() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun temperature(): Optional = body.temperature() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolChoice(): Optional = body.toolChoice() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tools(): Optional> = body.tools() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun topLogprobs(): Optional = body.topLogprobs() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun topP(): Optional = body.topP() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun user(): Optional = body.user() + + /** + * Returns the raw JSON value of [messages]. + * + * Unlike [messages], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _messages(): JsonField> = body._messages() + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _model(): JsonField = body._model() + + /** + * Returns the raw JSON value of [caching]. + * + * Unlike [caching], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _caching(): JsonField = body._caching() + + /** + * Returns the raw JSON value of [contextWindowFallbackDict]. + * + * Unlike [contextWindowFallbackDict], this method doesn't throw if the JSON field has an + * unexpected type. + */ + fun _contextWindowFallbackDict(): JsonField = + body._contextWindowFallbackDict() + + /** + * Returns the raw JSON value of [fallbacks]. + * + * Unlike [fallbacks], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _fallbacks(): JsonField> = body._fallbacks() + + /** + * Returns the raw JSON value of [frequencyPenalty]. + * + * Unlike [frequencyPenalty], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _frequencyPenalty(): JsonField = body._frequencyPenalty() + + /** + * Returns the raw JSON value of [functionCall]. + * + * Unlike [functionCall], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functionCall(): JsonField = body._functionCall() + + /** + * Returns the raw JSON value of [functions]. + * + * Unlike [functions], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functions(): JsonField> = body._functions() + + /** + * Returns the raw JSON value of [guardrails]. + * + * Unlike [guardrails], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _guardrails(): JsonField> = body._guardrails() + + /** + * Returns the raw JSON value of [logitBias]. + * + * Unlike [logitBias], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _logitBias(): JsonField = body._logitBias() + + /** + * Returns the raw JSON value of [logprobs]. + * + * Unlike [logprobs], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _logprobs(): JsonField = body._logprobs() + + /** + * Returns the raw JSON value of [maxTokens]. + * + * Unlike [maxTokens], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _maxTokens(): JsonField = body._maxTokens() + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [n]. + * + * Unlike [n], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _n(): JsonField = body._n() + + /** + * Returns the raw JSON value of [numRetries]. + * + * Unlike [numRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _numRetries(): JsonField = body._numRetries() + + /** + * Returns the raw JSON value of [parallelToolCalls]. + * + * Unlike [parallelToolCalls], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _parallelToolCalls(): JsonField = body._parallelToolCalls() + + /** + * Returns the raw JSON value of [presencePenalty]. + * + * Unlike [presencePenalty], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _presencePenalty(): JsonField = body._presencePenalty() + + /** + * Returns the raw JSON value of [responseFormat]. + * + * Unlike [responseFormat], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _responseFormat(): JsonField = body._responseFormat() + + /** + * Returns the raw JSON value of [seed]. + * + * Unlike [seed], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _seed(): JsonField = body._seed() + + /** + * Returns the raw JSON value of [serviceTier]. + * + * Unlike [serviceTier], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _serviceTier(): JsonField = body._serviceTier() + + /** + * Returns the raw JSON value of [stop]. + * + * Unlike [stop], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _stop(): JsonField = body._stop() + + /** + * Returns the raw JSON value of [stream]. + * + * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _stream(): JsonField = body._stream() + + /** + * Returns the raw JSON value of [streamOptions]. + * + * Unlike [streamOptions], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _streamOptions(): JsonField = body._streamOptions() + + /** + * Returns the raw JSON value of [temperature]. + * + * Unlike [temperature], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _temperature(): JsonField = body._temperature() + + /** + * Returns the raw JSON value of [toolChoice]. + * + * Unlike [toolChoice], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _toolChoice(): JsonField = body._toolChoice() + + /** + * Returns the raw JSON value of [tools]. + * + * Unlike [tools], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tools(): JsonField> = body._tools() + + /** + * Returns the raw JSON value of [topLogprobs]. + * + * Unlike [topLogprobs], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _topLogprobs(): JsonField = body._topLogprobs() + + /** + * Returns the raw JSON value of [topP]. + * + * Unlike [topP], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _topP(): JsonField = body._topP() + + /** + * Returns the raw JSON value of [user]. + * + * Unlike [user], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _user(): JsonField = body._user() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders - fun _additionalQueryParams(): QueryParams = additionalQueryParams + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [CompletionCreateParams]. + * + * The following fields are required: + * ```java + * .messages() + * .model() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CompletionCreateParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(completionCreateParams: CompletionCreateParams) = apply { + body = completionCreateParams.body.toBuilder() + additionalHeaders = completionCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = completionCreateParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [messages] + * - [model] + * - [caching] + * - [contextWindowFallbackDict] + * - [fallbacks] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + fun messages(messages: List) = apply { body.messages(messages) } + + /** + * Sets [Builder.messages] to an arbitrary JSON value. + * + * You should usually call [Builder.messages] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun messages(messages: JsonField>) = apply { body.messages(messages) } + + /** + * Adds a single [Message] to [messages]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMessage(message: Message) = apply { body.addMessage(message) } + + /** + * Alias for calling [addMessage] with `Message.ofChatCompletionUser(chatCompletionUser)`. + */ + fun addMessage(chatCompletionUser: Message.ChatCompletionUserMessage) = apply { + body.addMessage(chatCompletionUser) + } + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionAssistant(chatCompletionAssistant)`. + */ + fun addMessage(chatCompletionAssistant: Message.ChatCompletionAssistantMessage) = apply { + body.addMessage(chatCompletionAssistant) + } + + /** + * Alias for calling [addMessage] with `Message.ofChatCompletionTool(chatCompletionTool)`. + */ + fun addMessage(chatCompletionTool: Message.ChatCompletionToolMessage) = apply { + body.addMessage(chatCompletionTool) + } + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionSystem(chatCompletionSystem)`. + */ + fun addMessage(chatCompletionSystem: Message.ChatCompletionSystemMessage) = apply { + body.addMessage(chatCompletionSystem) + } + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionFunction(chatCompletionFunction)`. + */ + fun addMessage(chatCompletionFunction: Message.ChatCompletionFunctionMessage) = apply { + body.addMessage(chatCompletionFunction) + } + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionDeveloper(chatCompletionDeveloper)`. + */ + fun addMessage(chatCompletionDeveloper: Message.ChatCompletionDeveloperMessage) = apply { + body.addMessage(chatCompletionDeveloper) + } + + fun model(model: String) = apply { body.model(model) } + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun model(model: JsonField) = apply { body.model(model) } + + fun caching(caching: Boolean?) = apply { body.caching(caching) } + + /** + * Alias for [Builder.caching]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun caching(caching: Boolean) = caching(caching as Boolean?) + + /** Alias for calling [Builder.caching] with `caching.orElse(null)`. */ + fun caching(caching: Optional) = caching(caching.getOrNull()) + + /** + * Sets [Builder.caching] to an arbitrary JSON value. + * + * You should usually call [Builder.caching] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun caching(caching: JsonField) = apply { body.caching(caching) } + + fun contextWindowFallbackDict(contextWindowFallbackDict: ContextWindowFallbackDict?) = + apply { + body.contextWindowFallbackDict(contextWindowFallbackDict) + } + + /** + * Alias for calling [Builder.contextWindowFallbackDict] with + * `contextWindowFallbackDict.orElse(null)`. + */ + fun contextWindowFallbackDict( + contextWindowFallbackDict: Optional + ) = contextWindowFallbackDict(contextWindowFallbackDict.getOrNull()) + + /** + * Sets [Builder.contextWindowFallbackDict] to an arbitrary JSON value. + * + * You should usually call [Builder.contextWindowFallbackDict] with a well-typed + * [ContextWindowFallbackDict] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun contextWindowFallbackDict( + contextWindowFallbackDict: JsonField + ) = apply { body.contextWindowFallbackDict(contextWindowFallbackDict) } + + fun fallbacks(fallbacks: List?) = apply { body.fallbacks(fallbacks) } + + /** Alias for calling [Builder.fallbacks] with `fallbacks.orElse(null)`. */ + fun fallbacks(fallbacks: Optional>) = fallbacks(fallbacks.getOrNull()) + + /** + * Sets [Builder.fallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.fallbacks] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fallbacks(fallbacks: JsonField>) = apply { body.fallbacks(fallbacks) } + + /** + * Adds a single [String] to [fallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFallback(fallback: String) = apply { body.addFallback(fallback) } + + fun frequencyPenalty(frequencyPenalty: Double?) = apply { + body.frequencyPenalty(frequencyPenalty) + } + + /** + * Alias for [Builder.frequencyPenalty]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun frequencyPenalty(frequencyPenalty: Double) = + frequencyPenalty(frequencyPenalty as Double?) + + /** Alias for calling [Builder.frequencyPenalty] with `frequencyPenalty.orElse(null)`. */ + fun frequencyPenalty(frequencyPenalty: Optional) = + frequencyPenalty(frequencyPenalty.getOrNull()) + + /** + * Sets [Builder.frequencyPenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.frequencyPenalty] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun frequencyPenalty(frequencyPenalty: JsonField) = apply { + body.frequencyPenalty(frequencyPenalty) + } + + fun functionCall(functionCall: FunctionCall?) = apply { body.functionCall(functionCall) } + + /** Alias for calling [Builder.functionCall] with `functionCall.orElse(null)`. */ + fun functionCall(functionCall: Optional) = + functionCall(functionCall.getOrNull()) + + /** + * Sets [Builder.functionCall] to an arbitrary JSON value. + * + * You should usually call [Builder.functionCall] with a well-typed [FunctionCall] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functionCall(functionCall: JsonField) = apply { + body.functionCall(functionCall) + } + + /** Alias for calling [functionCall] with `FunctionCall.ofString(string)`. */ + fun functionCall(string: String) = apply { body.functionCall(string) } + + /** Alias for calling [functionCall] with `FunctionCall.ofUnionMember1(unionMember1)`. */ + fun functionCall(unionMember1: FunctionCall.UnionMember1) = apply { + body.functionCall(unionMember1) + } + + fun functions(functions: List?) = apply { body.functions(functions) } + + /** Alias for calling [Builder.functions] with `functions.orElse(null)`. */ + fun functions(functions: Optional>) = functions(functions.getOrNull()) + + /** + * Sets [Builder.functions] to an arbitrary JSON value. + * + * You should usually call [Builder.functions] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functions(functions: JsonField>) = apply { body.functions(functions) } + + /** + * Adds a single [Function] to [functions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFunction(function: Function) = apply { body.addFunction(function) } + + fun guardrails(guardrails: List?) = apply { body.guardrails(guardrails) } + + /** Alias for calling [Builder.guardrails] with `guardrails.orElse(null)`. */ + fun guardrails(guardrails: Optional>) = guardrails(guardrails.getOrNull()) + + /** + * Sets [Builder.guardrails] to an arbitrary JSON value. + * + * You should usually call [Builder.guardrails] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun guardrails(guardrails: JsonField>) = apply { body.guardrails(guardrails) } + + /** + * Adds a single [String] to [guardrails]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addGuardrail(guardrail: String) = apply { body.addGuardrail(guardrail) } + + fun logitBias(logitBias: LogitBias?) = apply { body.logitBias(logitBias) } + + /** Alias for calling [Builder.logitBias] with `logitBias.orElse(null)`. */ + fun logitBias(logitBias: Optional) = logitBias(logitBias.getOrNull()) + + /** + * Sets [Builder.logitBias] to an arbitrary JSON value. + * + * You should usually call [Builder.logitBias] with a well-typed [LogitBias] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun logitBias(logitBias: JsonField) = apply { body.logitBias(logitBias) } + + fun logprobs(logprobs: Boolean?) = apply { body.logprobs(logprobs) } + + /** + * Alias for [Builder.logprobs]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun logprobs(logprobs: Boolean) = logprobs(logprobs as Boolean?) + + /** Alias for calling [Builder.logprobs] with `logprobs.orElse(null)`. */ + fun logprobs(logprobs: Optional) = logprobs(logprobs.getOrNull()) + + /** + * Sets [Builder.logprobs] to an arbitrary JSON value. + * + * You should usually call [Builder.logprobs] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun logprobs(logprobs: JsonField) = apply { body.logprobs(logprobs) } + + fun maxTokens(maxTokens: Long?) = apply { body.maxTokens(maxTokens) } + + /** + * Alias for [Builder.maxTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxTokens(maxTokens: Long) = maxTokens(maxTokens as Long?) + + /** Alias for calling [Builder.maxTokens] with `maxTokens.orElse(null)`. */ + fun maxTokens(maxTokens: Optional) = maxTokens(maxTokens.getOrNull()) + + /** + * Sets [Builder.maxTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.maxTokens] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun maxTokens(maxTokens: JsonField) = apply { body.maxTokens(maxTokens) } + + fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } + + fun n(n: Long?) = apply { body.n(n) } + + /** + * Alias for [Builder.n]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun n(n: Long) = n(n as Long?) + + /** Alias for calling [Builder.n] with `n.orElse(null)`. */ + fun n(n: Optional) = n(n.getOrNull()) + + /** + * Sets [Builder.n] to an arbitrary JSON value. + * + * You should usually call [Builder.n] with a well-typed [Long] value instead. This method + * is primarily for setting the field to an undocumented or not yet supported value. + */ + fun n(n: JsonField) = apply { body.n(n) } + + fun numRetries(numRetries: Long?) = apply { body.numRetries(numRetries) } + + /** + * Alias for [Builder.numRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun numRetries(numRetries: Long) = numRetries(numRetries as Long?) + + /** Alias for calling [Builder.numRetries] with `numRetries.orElse(null)`. */ + fun numRetries(numRetries: Optional) = numRetries(numRetries.getOrNull()) + + /** + * Sets [Builder.numRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.numRetries] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun numRetries(numRetries: JsonField) = apply { body.numRetries(numRetries) } + + fun parallelToolCalls(parallelToolCalls: Boolean?) = apply { + body.parallelToolCalls(parallelToolCalls) + } + + /** + * Alias for [Builder.parallelToolCalls]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun parallelToolCalls(parallelToolCalls: Boolean) = + parallelToolCalls(parallelToolCalls as Boolean?) + + /** Alias for calling [Builder.parallelToolCalls] with `parallelToolCalls.orElse(null)`. */ + fun parallelToolCalls(parallelToolCalls: Optional) = + parallelToolCalls(parallelToolCalls.getOrNull()) + + /** + * Sets [Builder.parallelToolCalls] to an arbitrary JSON value. + * + * You should usually call [Builder.parallelToolCalls] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun parallelToolCalls(parallelToolCalls: JsonField) = apply { + body.parallelToolCalls(parallelToolCalls) + } + + fun presencePenalty(presencePenalty: Double?) = apply { + body.presencePenalty(presencePenalty) + } + + /** + * Alias for [Builder.presencePenalty]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun presencePenalty(presencePenalty: Double) = presencePenalty(presencePenalty as Double?) + + /** Alias for calling [Builder.presencePenalty] with `presencePenalty.orElse(null)`. */ + fun presencePenalty(presencePenalty: Optional) = + presencePenalty(presencePenalty.getOrNull()) + + /** + * Sets [Builder.presencePenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.presencePenalty] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun presencePenalty(presencePenalty: JsonField) = apply { + body.presencePenalty(presencePenalty) + } + + fun responseFormat(responseFormat: ResponseFormat?) = apply { + body.responseFormat(responseFormat) + } + + /** Alias for calling [Builder.responseFormat] with `responseFormat.orElse(null)`. */ + fun responseFormat(responseFormat: Optional) = + responseFormat(responseFormat.getOrNull()) + + /** + * Sets [Builder.responseFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.responseFormat] with a well-typed [ResponseFormat] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun responseFormat(responseFormat: JsonField) = apply { + body.responseFormat(responseFormat) + } + + fun seed(seed: Long?) = apply { body.seed(seed) } + + /** + * Alias for [Builder.seed]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun seed(seed: Long) = seed(seed as Long?) + + /** Alias for calling [Builder.seed] with `seed.orElse(null)`. */ + fun seed(seed: Optional) = seed(seed.getOrNull()) + + /** + * Sets [Builder.seed] to an arbitrary JSON value. + * + * You should usually call [Builder.seed] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun seed(seed: JsonField) = apply { body.seed(seed) } + + fun serviceTier(serviceTier: String?) = apply { body.serviceTier(serviceTier) } + + /** Alias for calling [Builder.serviceTier] with `serviceTier.orElse(null)`. */ + fun serviceTier(serviceTier: Optional) = serviceTier(serviceTier.getOrNull()) + + /** + * Sets [Builder.serviceTier] to an arbitrary JSON value. + * + * You should usually call [Builder.serviceTier] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun serviceTier(serviceTier: JsonField) = apply { body.serviceTier(serviceTier) } + + fun stop(stop: Stop?) = apply { body.stop(stop) } + + /** Alias for calling [Builder.stop] with `stop.orElse(null)`. */ + fun stop(stop: Optional) = stop(stop.getOrNull()) + + /** + * Sets [Builder.stop] to an arbitrary JSON value. + * + * You should usually call [Builder.stop] with a well-typed [Stop] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun stop(stop: JsonField) = apply { body.stop(stop) } + + /** Alias for calling [stop] with `Stop.ofString(string)`. */ + fun stop(string: String) = apply { body.stop(string) } + + /** Alias for calling [stop] with `Stop.ofStrings(strings)`. */ + fun stopOfStrings(strings: List) = apply { body.stopOfStrings(strings) } + + fun stream(stream: Boolean?) = apply { body.stream(stream) } + + /** + * Alias for [Builder.stream]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun stream(stream: Boolean) = stream(stream as Boolean?) + + /** Alias for calling [Builder.stream] with `stream.orElse(null)`. */ + fun stream(stream: Optional) = stream(stream.getOrNull()) + + /** + * Sets [Builder.stream] to an arbitrary JSON value. + * + * You should usually call [Builder.stream] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun stream(stream: JsonField) = apply { body.stream(stream) } + + fun streamOptions(streamOptions: StreamOptions?) = apply { + body.streamOptions(streamOptions) + } + + /** Alias for calling [Builder.streamOptions] with `streamOptions.orElse(null)`. */ + fun streamOptions(streamOptions: Optional) = + streamOptions(streamOptions.getOrNull()) + + /** + * Sets [Builder.streamOptions] to an arbitrary JSON value. + * + * You should usually call [Builder.streamOptions] with a well-typed [StreamOptions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun streamOptions(streamOptions: JsonField) = apply { + body.streamOptions(streamOptions) + } + + fun temperature(temperature: Double?) = apply { body.temperature(temperature) } + + /** + * Alias for [Builder.temperature]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun temperature(temperature: Double) = temperature(temperature as Double?) + + /** Alias for calling [Builder.temperature] with `temperature.orElse(null)`. */ + fun temperature(temperature: Optional) = temperature(temperature.getOrNull()) + + /** + * Sets [Builder.temperature] to an arbitrary JSON value. + * + * You should usually call [Builder.temperature] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun temperature(temperature: JsonField) = apply { body.temperature(temperature) } + + fun toolChoice(toolChoice: ToolChoice?) = apply { body.toolChoice(toolChoice) } + + /** Alias for calling [Builder.toolChoice] with `toolChoice.orElse(null)`. */ + fun toolChoice(toolChoice: Optional) = toolChoice(toolChoice.getOrNull()) + + /** + * Sets [Builder.toolChoice] to an arbitrary JSON value. + * + * You should usually call [Builder.toolChoice] with a well-typed [ToolChoice] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun toolChoice(toolChoice: JsonField) = apply { body.toolChoice(toolChoice) } + + /** Alias for calling [toolChoice] with `ToolChoice.ofString(string)`. */ + fun toolChoice(string: String) = apply { body.toolChoice(string) } + + /** Alias for calling [toolChoice] with `ToolChoice.ofUnionMember1(unionMember1)`. */ + fun toolChoice(unionMember1: ToolChoice.UnionMember1) = apply { + body.toolChoice(unionMember1) + } + + fun tools(tools: List?) = apply { body.tools(tools) } + + /** Alias for calling [Builder.tools] with `tools.orElse(null)`. */ + fun tools(tools: Optional>) = tools(tools.getOrNull()) + + /** + * Sets [Builder.tools] to an arbitrary JSON value. + * + * You should usually call [Builder.tools] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tools(tools: JsonField>) = apply { body.tools(tools) } + + /** + * Adds a single [Tool] to [tools]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTool(tool: Tool) = apply { body.addTool(tool) } + + fun topLogprobs(topLogprobs: Long?) = apply { body.topLogprobs(topLogprobs) } + + /** + * Alias for [Builder.topLogprobs]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun topLogprobs(topLogprobs: Long) = topLogprobs(topLogprobs as Long?) + + /** Alias for calling [Builder.topLogprobs] with `topLogprobs.orElse(null)`. */ + fun topLogprobs(topLogprobs: Optional) = topLogprobs(topLogprobs.getOrNull()) + + /** + * Sets [Builder.topLogprobs] to an arbitrary JSON value. + * + * You should usually call [Builder.topLogprobs] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun topLogprobs(topLogprobs: JsonField) = apply { body.topLogprobs(topLogprobs) } + + fun topP(topP: Double?) = apply { body.topP(topP) } + + /** + * Alias for [Builder.topP]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun topP(topP: Double) = topP(topP as Double?) + + /** Alias for calling [Builder.topP] with `topP.orElse(null)`. */ + fun topP(topP: Optional) = topP(topP.getOrNull()) + + /** + * Sets [Builder.topP] to an arbitrary JSON value. + * + * You should usually call [Builder.topP] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun topP(topP: JsonField) = apply { body.topP(topP) } + + fun user(user: String?) = apply { body.user(user) } + + /** Alias for calling [Builder.user] with `user.orElse(null)`. */ + fun user(user: Optional) = user(user.getOrNull()) + + /** + * Sets [Builder.user] to an arbitrary JSON value. + * + * You should usually call [Builder.user] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun user(user: JsonField) = apply { body.user(user) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [CompletionCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .messages() + * .model() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): CompletionCreateParams = + CompletionCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val messages: JsonField>, + private val model: JsonField, + private val caching: JsonField, + private val contextWindowFallbackDict: JsonField, + private val fallbacks: JsonField>, + private val frequencyPenalty: JsonField, + private val functionCall: JsonField, + private val functions: JsonField>, + private val guardrails: JsonField>, + private val logitBias: JsonField, + private val logprobs: JsonField, + private val maxTokens: JsonField, + private val metadata: JsonField, + private val n: JsonField, + private val numRetries: JsonField, + private val parallelToolCalls: JsonField, + private val presencePenalty: JsonField, + private val responseFormat: JsonField, + private val seed: JsonField, + private val serviceTier: JsonField, + private val stop: JsonField, + private val stream: JsonField, + private val streamOptions: JsonField, + private val temperature: JsonField, + private val toolChoice: JsonField, + private val tools: JsonField>, + private val topLogprobs: JsonField, + private val topP: JsonField, + private val user: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("messages") + @ExcludeMissing + messages: JsonField> = JsonMissing.of(), + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of(), + @JsonProperty("caching") @ExcludeMissing caching: JsonField = JsonMissing.of(), + @JsonProperty("context_window_fallback_dict") + @ExcludeMissing + contextWindowFallbackDict: JsonField = JsonMissing.of(), + @JsonProperty("fallbacks") + @ExcludeMissing + fallbacks: JsonField> = JsonMissing.of(), + @JsonProperty("frequency_penalty") + @ExcludeMissing + frequencyPenalty: JsonField = JsonMissing.of(), + @JsonProperty("function_call") + @ExcludeMissing + functionCall: JsonField = JsonMissing.of(), + @JsonProperty("functions") + @ExcludeMissing + functions: JsonField> = JsonMissing.of(), + @JsonProperty("guardrails") + @ExcludeMissing + guardrails: JsonField> = JsonMissing.of(), + @JsonProperty("logit_bias") + @ExcludeMissing + logitBias: JsonField = JsonMissing.of(), + @JsonProperty("logprobs") + @ExcludeMissing + logprobs: JsonField = JsonMissing.of(), + @JsonProperty("max_tokens") + @ExcludeMissing + maxTokens: JsonField = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("n") @ExcludeMissing n: JsonField = JsonMissing.of(), + @JsonProperty("num_retries") + @ExcludeMissing + numRetries: JsonField = JsonMissing.of(), + @JsonProperty("parallel_tool_calls") + @ExcludeMissing + parallelToolCalls: JsonField = JsonMissing.of(), + @JsonProperty("presence_penalty") + @ExcludeMissing + presencePenalty: JsonField = JsonMissing.of(), + @JsonProperty("response_format") + @ExcludeMissing + responseFormat: JsonField = JsonMissing.of(), + @JsonProperty("seed") @ExcludeMissing seed: JsonField = JsonMissing.of(), + @JsonProperty("service_tier") + @ExcludeMissing + serviceTier: JsonField = JsonMissing.of(), + @JsonProperty("stop") @ExcludeMissing stop: JsonField = JsonMissing.of(), + @JsonProperty("stream") @ExcludeMissing stream: JsonField = JsonMissing.of(), + @JsonProperty("stream_options") + @ExcludeMissing + streamOptions: JsonField = JsonMissing.of(), + @JsonProperty("temperature") + @ExcludeMissing + temperature: JsonField = JsonMissing.of(), + @JsonProperty("tool_choice") + @ExcludeMissing + toolChoice: JsonField = JsonMissing.of(), + @JsonProperty("tools") @ExcludeMissing tools: JsonField> = JsonMissing.of(), + @JsonProperty("top_logprobs") + @ExcludeMissing + topLogprobs: JsonField = JsonMissing.of(), + @JsonProperty("top_p") @ExcludeMissing topP: JsonField = JsonMissing.of(), + @JsonProperty("user") @ExcludeMissing user: JsonField = JsonMissing.of(), + ) : this( + messages, + model, + caching, + contextWindowFallbackDict, + fallbacks, + frequencyPenalty, + functionCall, + functions, + guardrails, + logitBias, + logprobs, + maxTokens, + metadata, + n, + numRetries, + parallelToolCalls, + presencePenalty, + responseFormat, + seed, + serviceTier, + stop, + stream, + streamOptions, + temperature, + toolChoice, + tools, + topLogprobs, + topP, + user, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun messages(): List = messages.getRequired("messages") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun model(): String = model.getRequired("model") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun caching(): Optional = caching.getOptional("caching") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun contextWindowFallbackDict(): Optional = + contextWindowFallbackDict.getOptional("context_window_fallback_dict") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fallbacks(): Optional> = fallbacks.getOptional("fallbacks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun frequencyPenalty(): Optional = frequencyPenalty.getOptional("frequency_penalty") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functionCall(): Optional = functionCall.getOptional("function_call") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functions(): Optional> = functions.getOptional("functions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun guardrails(): Optional> = guardrails.getOptional("guardrails") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logitBias(): Optional = logitBias.getOptional("logit_bias") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logprobs(): Optional = logprobs.getOptional("logprobs") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxTokens(): Optional = maxTokens.getOptional("max_tokens") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun n(): Optional = n.getOptional("n") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun numRetries(): Optional = numRetries.getOptional("num_retries") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun parallelToolCalls(): Optional = + parallelToolCalls.getOptional("parallel_tool_calls") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun presencePenalty(): Optional = presencePenalty.getOptional("presence_penalty") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun responseFormat(): Optional = + responseFormat.getOptional("response_format") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun seed(): Optional = seed.getOptional("seed") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun serviceTier(): Optional = serviceTier.getOptional("service_tier") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stop(): Optional = stop.getOptional("stop") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stream(): Optional = stream.getOptional("stream") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun streamOptions(): Optional = streamOptions.getOptional("stream_options") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun temperature(): Optional = temperature.getOptional("temperature") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolChoice(): Optional = toolChoice.getOptional("tool_choice") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tools(): Optional> = tools.getOptional("tools") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun topLogprobs(): Optional = topLogprobs.getOptional("top_logprobs") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun topP(): Optional = topP.getOptional("top_p") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun user(): Optional = user.getOptional("user") + + /** + * Returns the raw JSON value of [messages]. + * + * Unlike [messages], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("messages") + @ExcludeMissing + fun _messages(): JsonField> = messages + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + /** + * Returns the raw JSON value of [caching]. + * + * Unlike [caching], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("caching") @ExcludeMissing fun _caching(): JsonField = caching + + /** + * Returns the raw JSON value of [contextWindowFallbackDict]. + * + * Unlike [contextWindowFallbackDict], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("context_window_fallback_dict") + @ExcludeMissing + fun _contextWindowFallbackDict(): JsonField = + contextWindowFallbackDict + + /** + * Returns the raw JSON value of [fallbacks]. + * + * Unlike [fallbacks], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fallbacks") + @ExcludeMissing + fun _fallbacks(): JsonField> = fallbacks + + /** + * Returns the raw JSON value of [frequencyPenalty]. + * + * Unlike [frequencyPenalty], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("frequency_penalty") + @ExcludeMissing + fun _frequencyPenalty(): JsonField = frequencyPenalty + + /** + * Returns the raw JSON value of [functionCall]. + * + * Unlike [functionCall], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_call") + @ExcludeMissing + fun _functionCall(): JsonField = functionCall + + /** + * Returns the raw JSON value of [functions]. + * + * Unlike [functions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("functions") + @ExcludeMissing + fun _functions(): JsonField> = functions + + /** + * Returns the raw JSON value of [guardrails]. + * + * Unlike [guardrails], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("guardrails") + @ExcludeMissing + fun _guardrails(): JsonField> = guardrails + + /** + * Returns the raw JSON value of [logitBias]. + * + * Unlike [logitBias], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("logit_bias") + @ExcludeMissing + fun _logitBias(): JsonField = logitBias + + /** + * Returns the raw JSON value of [logprobs]. + * + * Unlike [logprobs], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("logprobs") @ExcludeMissing fun _logprobs(): JsonField = logprobs + + /** + * Returns the raw JSON value of [maxTokens]. + * + * Unlike [maxTokens], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("max_tokens") @ExcludeMissing fun _maxTokens(): JsonField = maxTokens + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [n]. + * + * Unlike [n], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("n") @ExcludeMissing fun _n(): JsonField = n + + /** + * Returns the raw JSON value of [numRetries]. + * + * Unlike [numRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("num_retries") @ExcludeMissing fun _numRetries(): JsonField = numRetries + + /** + * Returns the raw JSON value of [parallelToolCalls]. + * + * Unlike [parallelToolCalls], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("parallel_tool_calls") + @ExcludeMissing + fun _parallelToolCalls(): JsonField = parallelToolCalls + + /** + * Returns the raw JSON value of [presencePenalty]. + * + * Unlike [presencePenalty], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("presence_penalty") + @ExcludeMissing + fun _presencePenalty(): JsonField = presencePenalty + + /** + * Returns the raw JSON value of [responseFormat]. + * + * Unlike [responseFormat], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_format") + @ExcludeMissing + fun _responseFormat(): JsonField = responseFormat + + /** + * Returns the raw JSON value of [seed]. + * + * Unlike [seed], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("seed") @ExcludeMissing fun _seed(): JsonField = seed + + /** + * Returns the raw JSON value of [serviceTier]. + * + * Unlike [serviceTier], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("service_tier") + @ExcludeMissing + fun _serviceTier(): JsonField = serviceTier + + /** + * Returns the raw JSON value of [stop]. + * + * Unlike [stop], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("stop") @ExcludeMissing fun _stop(): JsonField = stop + + /** + * Returns the raw JSON value of [stream]. + * + * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("stream") @ExcludeMissing fun _stream(): JsonField = stream + + /** + * Returns the raw JSON value of [streamOptions]. + * + * Unlike [streamOptions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("stream_options") + @ExcludeMissing + fun _streamOptions(): JsonField = streamOptions + + /** + * Returns the raw JSON value of [temperature]. + * + * Unlike [temperature], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("temperature") + @ExcludeMissing + fun _temperature(): JsonField = temperature + + /** + * Returns the raw JSON value of [toolChoice]. + * + * Unlike [toolChoice], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_choice") + @ExcludeMissing + fun _toolChoice(): JsonField = toolChoice + + /** + * Returns the raw JSON value of [tools]. + * + * Unlike [tools], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonField> = tools + + /** + * Returns the raw JSON value of [topLogprobs]. + * + * Unlike [topLogprobs], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("top_logprobs") + @ExcludeMissing + fun _topLogprobs(): JsonField = topLogprobs + + /** + * Returns the raw JSON value of [topP]. + * + * Unlike [topP], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("top_p") @ExcludeMissing fun _topP(): JsonField = topP + + /** + * Returns the raw JSON value of [user]. + * + * Unlike [user], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user") @ExcludeMissing fun _user(): JsonField = user + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .messages() + * .model() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var messages: JsonField>? = null + private var model: JsonField? = null + private var caching: JsonField = JsonMissing.of() + private var contextWindowFallbackDict: JsonField = + JsonMissing.of() + private var fallbacks: JsonField>? = null + private var frequencyPenalty: JsonField = JsonMissing.of() + private var functionCall: JsonField = JsonMissing.of() + private var functions: JsonField>? = null + private var guardrails: JsonField>? = null + private var logitBias: JsonField = JsonMissing.of() + private var logprobs: JsonField = JsonMissing.of() + private var maxTokens: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var n: JsonField = JsonMissing.of() + private var numRetries: JsonField = JsonMissing.of() + private var parallelToolCalls: JsonField = JsonMissing.of() + private var presencePenalty: JsonField = JsonMissing.of() + private var responseFormat: JsonField = JsonMissing.of() + private var seed: JsonField = JsonMissing.of() + private var serviceTier: JsonField = JsonMissing.of() + private var stop: JsonField = JsonMissing.of() + private var stream: JsonField = JsonMissing.of() + private var streamOptions: JsonField = JsonMissing.of() + private var temperature: JsonField = JsonMissing.of() + private var toolChoice: JsonField = JsonMissing.of() + private var tools: JsonField>? = null + private var topLogprobs: JsonField = JsonMissing.of() + private var topP: JsonField = JsonMissing.of() + private var user: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + messages = body.messages.map { it.toMutableList() } + model = body.model + caching = body.caching + contextWindowFallbackDict = body.contextWindowFallbackDict + fallbacks = body.fallbacks.map { it.toMutableList() } + frequencyPenalty = body.frequencyPenalty + functionCall = body.functionCall + functions = body.functions.map { it.toMutableList() } + guardrails = body.guardrails.map { it.toMutableList() } + logitBias = body.logitBias + logprobs = body.logprobs + maxTokens = body.maxTokens + metadata = body.metadata + n = body.n + numRetries = body.numRetries + parallelToolCalls = body.parallelToolCalls + presencePenalty = body.presencePenalty + responseFormat = body.responseFormat + seed = body.seed + serviceTier = body.serviceTier + stop = body.stop + stream = body.stream + streamOptions = body.streamOptions + temperature = body.temperature + toolChoice = body.toolChoice + tools = body.tools.map { it.toMutableList() } + topLogprobs = body.topLogprobs + topP = body.topP + user = body.user + additionalProperties = body.additionalProperties.toMutableMap() + } + + fun messages(messages: List) = messages(JsonField.of(messages)) + + /** + * Sets [Builder.messages] to an arbitrary JSON value. + * + * You should usually call [Builder.messages] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun messages(messages: JsonField>) = apply { + this.messages = messages.map { it.toMutableList() } + } + + /** + * Adds a single [Message] to [messages]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMessage(message: Message) = apply { + messages = + (messages ?: JsonField.of(mutableListOf())).also { + checkKnown("messages", it).add(message) + } + } + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionUser(chatCompletionUser)`. + */ + fun addMessage(chatCompletionUser: Message.ChatCompletionUserMessage) = + addMessage(Message.ofChatCompletionUser(chatCompletionUser)) + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionAssistant(chatCompletionAssistant)`. + */ + fun addMessage(chatCompletionAssistant: Message.ChatCompletionAssistantMessage) = + addMessage(Message.ofChatCompletionAssistant(chatCompletionAssistant)) + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionTool(chatCompletionTool)`. + */ + fun addMessage(chatCompletionTool: Message.ChatCompletionToolMessage) = + addMessage(Message.ofChatCompletionTool(chatCompletionTool)) + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionSystem(chatCompletionSystem)`. + */ + fun addMessage(chatCompletionSystem: Message.ChatCompletionSystemMessage) = + addMessage(Message.ofChatCompletionSystem(chatCompletionSystem)) + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionFunction(chatCompletionFunction)`. + */ + fun addMessage(chatCompletionFunction: Message.ChatCompletionFunctionMessage) = + addMessage(Message.ofChatCompletionFunction(chatCompletionFunction)) + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionDeveloper(chatCompletionDeveloper)`. + */ + fun addMessage(chatCompletionDeveloper: Message.ChatCompletionDeveloperMessage) = + addMessage(Message.ofChatCompletionDeveloper(chatCompletionDeveloper)) + + fun model(model: String) = model(JsonField.of(model)) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun caching(caching: Boolean?) = caching(JsonField.ofNullable(caching)) + + /** + * Alias for [Builder.caching]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun caching(caching: Boolean) = caching(caching as Boolean?) + + /** Alias for calling [Builder.caching] with `caching.orElse(null)`. */ + fun caching(caching: Optional) = caching(caching.getOrNull()) + + /** + * Sets [Builder.caching] to an arbitrary JSON value. + * + * You should usually call [Builder.caching] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun caching(caching: JsonField) = apply { this.caching = caching } + + fun contextWindowFallbackDict(contextWindowFallbackDict: ContextWindowFallbackDict?) = + contextWindowFallbackDict(JsonField.ofNullable(contextWindowFallbackDict)) + + /** + * Alias for calling [Builder.contextWindowFallbackDict] with + * `contextWindowFallbackDict.orElse(null)`. + */ + fun contextWindowFallbackDict( + contextWindowFallbackDict: Optional + ) = contextWindowFallbackDict(contextWindowFallbackDict.getOrNull()) + + /** + * Sets [Builder.contextWindowFallbackDict] to an arbitrary JSON value. + * + * You should usually call [Builder.contextWindowFallbackDict] with a well-typed + * [ContextWindowFallbackDict] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun contextWindowFallbackDict( + contextWindowFallbackDict: JsonField + ) = apply { this.contextWindowFallbackDict = contextWindowFallbackDict } + + fun fallbacks(fallbacks: List?) = fallbacks(JsonField.ofNullable(fallbacks)) + + /** Alias for calling [Builder.fallbacks] with `fallbacks.orElse(null)`. */ + fun fallbacks(fallbacks: Optional>) = fallbacks(fallbacks.getOrNull()) + + /** + * Sets [Builder.fallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.fallbacks] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fallbacks(fallbacks: JsonField>) = apply { + this.fallbacks = fallbacks.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [fallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFallback(fallback: String) = apply { + fallbacks = + (fallbacks ?: JsonField.of(mutableListOf())).also { + checkKnown("fallbacks", it).add(fallback) + } + } + + fun frequencyPenalty(frequencyPenalty: Double?) = + frequencyPenalty(JsonField.ofNullable(frequencyPenalty)) + + /** + * Alias for [Builder.frequencyPenalty]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun frequencyPenalty(frequencyPenalty: Double) = + frequencyPenalty(frequencyPenalty as Double?) + + /** + * Alias for calling [Builder.frequencyPenalty] with `frequencyPenalty.orElse(null)`. + */ + fun frequencyPenalty(frequencyPenalty: Optional) = + frequencyPenalty(frequencyPenalty.getOrNull()) + + /** + * Sets [Builder.frequencyPenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.frequencyPenalty] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun frequencyPenalty(frequencyPenalty: JsonField) = apply { + this.frequencyPenalty = frequencyPenalty + } + + fun functionCall(functionCall: FunctionCall?) = + functionCall(JsonField.ofNullable(functionCall)) + + /** Alias for calling [Builder.functionCall] with `functionCall.orElse(null)`. */ + fun functionCall(functionCall: Optional) = + functionCall(functionCall.getOrNull()) + + /** + * Sets [Builder.functionCall] to an arbitrary JSON value. + * + * You should usually call [Builder.functionCall] with a well-typed [FunctionCall] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functionCall(functionCall: JsonField) = apply { + this.functionCall = functionCall + } + + /** Alias for calling [functionCall] with `FunctionCall.ofString(string)`. */ + fun functionCall(string: String) = functionCall(FunctionCall.ofString(string)) + + /** + * Alias for calling [functionCall] with `FunctionCall.ofUnionMember1(unionMember1)`. + */ + fun functionCall(unionMember1: FunctionCall.UnionMember1) = + functionCall(FunctionCall.ofUnionMember1(unionMember1)) + + fun functions(functions: List?) = functions(JsonField.ofNullable(functions)) + + /** Alias for calling [Builder.functions] with `functions.orElse(null)`. */ + fun functions(functions: Optional>) = functions(functions.getOrNull()) + + /** + * Sets [Builder.functions] to an arbitrary JSON value. + * + * You should usually call [Builder.functions] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functions(functions: JsonField>) = apply { + this.functions = functions.map { it.toMutableList() } + } + + /** + * Adds a single [Function] to [functions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFunction(function: Function) = apply { + functions = + (functions ?: JsonField.of(mutableListOf())).also { + checkKnown("functions", it).add(function) + } + } + + fun guardrails(guardrails: List?) = guardrails(JsonField.ofNullable(guardrails)) + + /** Alias for calling [Builder.guardrails] with `guardrails.orElse(null)`. */ + fun guardrails(guardrails: Optional>) = guardrails(guardrails.getOrNull()) + + /** + * Sets [Builder.guardrails] to an arbitrary JSON value. + * + * You should usually call [Builder.guardrails] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun guardrails(guardrails: JsonField>) = apply { + this.guardrails = guardrails.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [guardrails]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addGuardrail(guardrail: String) = apply { + guardrails = + (guardrails ?: JsonField.of(mutableListOf())).also { + checkKnown("guardrails", it).add(guardrail) + } + } + + fun logitBias(logitBias: LogitBias?) = logitBias(JsonField.ofNullable(logitBias)) + + /** Alias for calling [Builder.logitBias] with `logitBias.orElse(null)`. */ + fun logitBias(logitBias: Optional) = logitBias(logitBias.getOrNull()) + + /** + * Sets [Builder.logitBias] to an arbitrary JSON value. + * + * You should usually call [Builder.logitBias] with a well-typed [LogitBias] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun logitBias(logitBias: JsonField) = apply { this.logitBias = logitBias } + + fun logprobs(logprobs: Boolean?) = logprobs(JsonField.ofNullable(logprobs)) + + /** + * Alias for [Builder.logprobs]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun logprobs(logprobs: Boolean) = logprobs(logprobs as Boolean?) + + /** Alias for calling [Builder.logprobs] with `logprobs.orElse(null)`. */ + fun logprobs(logprobs: Optional) = logprobs(logprobs.getOrNull()) + + /** + * Sets [Builder.logprobs] to an arbitrary JSON value. + * + * You should usually call [Builder.logprobs] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun logprobs(logprobs: JsonField) = apply { this.logprobs = logprobs } + + fun maxTokens(maxTokens: Long?) = maxTokens(JsonField.ofNullable(maxTokens)) + + /** + * Alias for [Builder.maxTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxTokens(maxTokens: Long) = maxTokens(maxTokens as Long?) + + /** Alias for calling [Builder.maxTokens] with `maxTokens.orElse(null)`. */ + fun maxTokens(maxTokens: Optional) = maxTokens(maxTokens.getOrNull()) + + /** + * Sets [Builder.maxTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.maxTokens] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxTokens(maxTokens: JsonField) = apply { this.maxTokens = maxTokens } + + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun n(n: Long?) = n(JsonField.ofNullable(n)) + + /** + * Alias for [Builder.n]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun n(n: Long) = n(n as Long?) + + /** Alias for calling [Builder.n] with `n.orElse(null)`. */ + fun n(n: Optional) = n(n.getOrNull()) + + /** + * Sets [Builder.n] to an arbitrary JSON value. + * + * You should usually call [Builder.n] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun n(n: JsonField) = apply { this.n = n } + + fun numRetries(numRetries: Long?) = numRetries(JsonField.ofNullable(numRetries)) + + /** + * Alias for [Builder.numRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun numRetries(numRetries: Long) = numRetries(numRetries as Long?) + + /** Alias for calling [Builder.numRetries] with `numRetries.orElse(null)`. */ + fun numRetries(numRetries: Optional) = numRetries(numRetries.getOrNull()) + + /** + * Sets [Builder.numRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.numRetries] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun numRetries(numRetries: JsonField) = apply { this.numRetries = numRetries } + + fun parallelToolCalls(parallelToolCalls: Boolean?) = + parallelToolCalls(JsonField.ofNullable(parallelToolCalls)) + + /** + * Alias for [Builder.parallelToolCalls]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun parallelToolCalls(parallelToolCalls: Boolean) = + parallelToolCalls(parallelToolCalls as Boolean?) + + /** + * Alias for calling [Builder.parallelToolCalls] with `parallelToolCalls.orElse(null)`. + */ + fun parallelToolCalls(parallelToolCalls: Optional) = + parallelToolCalls(parallelToolCalls.getOrNull()) + + /** + * Sets [Builder.parallelToolCalls] to an arbitrary JSON value. + * + * You should usually call [Builder.parallelToolCalls] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun parallelToolCalls(parallelToolCalls: JsonField) = apply { + this.parallelToolCalls = parallelToolCalls + } + + fun presencePenalty(presencePenalty: Double?) = + presencePenalty(JsonField.ofNullable(presencePenalty)) + + /** + * Alias for [Builder.presencePenalty]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun presencePenalty(presencePenalty: Double) = + presencePenalty(presencePenalty as Double?) + + /** Alias for calling [Builder.presencePenalty] with `presencePenalty.orElse(null)`. */ + fun presencePenalty(presencePenalty: Optional) = + presencePenalty(presencePenalty.getOrNull()) + + /** + * Sets [Builder.presencePenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.presencePenalty] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun presencePenalty(presencePenalty: JsonField) = apply { + this.presencePenalty = presencePenalty + } + + fun responseFormat(responseFormat: ResponseFormat?) = + responseFormat(JsonField.ofNullable(responseFormat)) + + /** Alias for calling [Builder.responseFormat] with `responseFormat.orElse(null)`. */ + fun responseFormat(responseFormat: Optional) = + responseFormat(responseFormat.getOrNull()) + + /** + * Sets [Builder.responseFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.responseFormat] with a well-typed [ResponseFormat] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun responseFormat(responseFormat: JsonField) = apply { + this.responseFormat = responseFormat + } + + fun seed(seed: Long?) = seed(JsonField.ofNullable(seed)) + + /** + * Alias for [Builder.seed]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun seed(seed: Long) = seed(seed as Long?) + + /** Alias for calling [Builder.seed] with `seed.orElse(null)`. */ + fun seed(seed: Optional) = seed(seed.getOrNull()) + + /** + * Sets [Builder.seed] to an arbitrary JSON value. + * + * You should usually call [Builder.seed] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun seed(seed: JsonField) = apply { this.seed = seed } + + fun serviceTier(serviceTier: String?) = serviceTier(JsonField.ofNullable(serviceTier)) + + /** Alias for calling [Builder.serviceTier] with `serviceTier.orElse(null)`. */ + fun serviceTier(serviceTier: Optional) = serviceTier(serviceTier.getOrNull()) + + /** + * Sets [Builder.serviceTier] to an arbitrary JSON value. + * + * You should usually call [Builder.serviceTier] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun serviceTier(serviceTier: JsonField) = apply { + this.serviceTier = serviceTier + } + + fun stop(stop: Stop?) = stop(JsonField.ofNullable(stop)) + + /** Alias for calling [Builder.stop] with `stop.orElse(null)`. */ + fun stop(stop: Optional) = stop(stop.getOrNull()) + + /** + * Sets [Builder.stop] to an arbitrary JSON value. + * + * You should usually call [Builder.stop] with a well-typed [Stop] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun stop(stop: JsonField) = apply { this.stop = stop } + + /** Alias for calling [stop] with `Stop.ofString(string)`. */ + fun stop(string: String) = stop(Stop.ofString(string)) + + /** Alias for calling [stop] with `Stop.ofStrings(strings)`. */ + fun stopOfStrings(strings: List) = stop(Stop.ofStrings(strings)) + + fun stream(stream: Boolean?) = stream(JsonField.ofNullable(stream)) + + /** + * Alias for [Builder.stream]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun stream(stream: Boolean) = stream(stream as Boolean?) + + /** Alias for calling [Builder.stream] with `stream.orElse(null)`. */ + fun stream(stream: Optional) = stream(stream.getOrNull()) + + /** + * Sets [Builder.stream] to an arbitrary JSON value. + * + * You should usually call [Builder.stream] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun stream(stream: JsonField) = apply { this.stream = stream } + + fun streamOptions(streamOptions: StreamOptions?) = + streamOptions(JsonField.ofNullable(streamOptions)) + + /** Alias for calling [Builder.streamOptions] with `streamOptions.orElse(null)`. */ + fun streamOptions(streamOptions: Optional) = + streamOptions(streamOptions.getOrNull()) + + /** + * Sets [Builder.streamOptions] to an arbitrary JSON value. + * + * You should usually call [Builder.streamOptions] with a well-typed [StreamOptions] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun streamOptions(streamOptions: JsonField) = apply { + this.streamOptions = streamOptions + } + + fun temperature(temperature: Double?) = temperature(JsonField.ofNullable(temperature)) + + /** + * Alias for [Builder.temperature]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun temperature(temperature: Double) = temperature(temperature as Double?) + + /** Alias for calling [Builder.temperature] with `temperature.orElse(null)`. */ + fun temperature(temperature: Optional) = temperature(temperature.getOrNull()) + + /** + * Sets [Builder.temperature] to an arbitrary JSON value. + * + * You should usually call [Builder.temperature] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun temperature(temperature: JsonField) = apply { + this.temperature = temperature + } + + fun toolChoice(toolChoice: ToolChoice?) = toolChoice(JsonField.ofNullable(toolChoice)) + + /** Alias for calling [Builder.toolChoice] with `toolChoice.orElse(null)`. */ + fun toolChoice(toolChoice: Optional) = toolChoice(toolChoice.getOrNull()) + + /** + * Sets [Builder.toolChoice] to an arbitrary JSON value. + * + * You should usually call [Builder.toolChoice] with a well-typed [ToolChoice] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun toolChoice(toolChoice: JsonField) = apply { + this.toolChoice = toolChoice + } + + /** Alias for calling [toolChoice] with `ToolChoice.ofString(string)`. */ + fun toolChoice(string: String) = toolChoice(ToolChoice.ofString(string)) + + /** Alias for calling [toolChoice] with `ToolChoice.ofUnionMember1(unionMember1)`. */ + fun toolChoice(unionMember1: ToolChoice.UnionMember1) = + toolChoice(ToolChoice.ofUnionMember1(unionMember1)) + + fun tools(tools: List?) = tools(JsonField.ofNullable(tools)) + + /** Alias for calling [Builder.tools] with `tools.orElse(null)`. */ + fun tools(tools: Optional>) = tools(tools.getOrNull()) + + /** + * Sets [Builder.tools] to an arbitrary JSON value. + * + * You should usually call [Builder.tools] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tools(tools: JsonField>) = apply { + this.tools = tools.map { it.toMutableList() } + } + + /** + * Adds a single [Tool] to [tools]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTool(tool: Tool) = apply { + tools = + (tools ?: JsonField.of(mutableListOf())).also { + checkKnown("tools", it).add(tool) + } + } + + fun topLogprobs(topLogprobs: Long?) = topLogprobs(JsonField.ofNullable(topLogprobs)) + + /** + * Alias for [Builder.topLogprobs]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun topLogprobs(topLogprobs: Long) = topLogprobs(topLogprobs as Long?) + + /** Alias for calling [Builder.topLogprobs] with `topLogprobs.orElse(null)`. */ + fun topLogprobs(topLogprobs: Optional) = topLogprobs(topLogprobs.getOrNull()) + + /** + * Sets [Builder.topLogprobs] to an arbitrary JSON value. + * + * You should usually call [Builder.topLogprobs] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun topLogprobs(topLogprobs: JsonField) = apply { this.topLogprobs = topLogprobs } + + fun topP(topP: Double?) = topP(JsonField.ofNullable(topP)) + + /** + * Alias for [Builder.topP]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun topP(topP: Double) = topP(topP as Double?) + + /** Alias for calling [Builder.topP] with `topP.orElse(null)`. */ + fun topP(topP: Optional) = topP(topP.getOrNull()) + + /** + * Sets [Builder.topP] to an arbitrary JSON value. + * + * You should usually call [Builder.topP] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun topP(topP: JsonField) = apply { this.topP = topP } + + fun user(user: String?) = user(JsonField.ofNullable(user)) + + /** Alias for calling [Builder.user] with `user.orElse(null)`. */ + fun user(user: Optional) = user(user.getOrNull()) + + /** + * Sets [Builder.user] to an arbitrary JSON value. + * + * You should usually call [Builder.user] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun user(user: JsonField) = apply { this.user = user } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .messages() + * .model() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("messages", messages).map { it.toImmutable() }, + checkRequired("model", model), + caching, + contextWindowFallbackDict, + (fallbacks ?: JsonMissing.of()).map { it.toImmutable() }, + frequencyPenalty, + functionCall, + (functions ?: JsonMissing.of()).map { it.toImmutable() }, + (guardrails ?: JsonMissing.of()).map { it.toImmutable() }, + logitBias, + logprobs, + maxTokens, + metadata, + n, + numRetries, + parallelToolCalls, + presencePenalty, + responseFormat, + seed, + serviceTier, + stop, + stream, + streamOptions, + temperature, + toolChoice, + (tools ?: JsonMissing.of()).map { it.toImmutable() }, + topLogprobs, + topP, + user, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + messages().forEach { it.validate() } + model() + caching() + contextWindowFallbackDict().ifPresent { it.validate() } + fallbacks() + frequencyPenalty() + functionCall().ifPresent { it.validate() } + functions().ifPresent { it.forEach { it.validate() } } + guardrails() + logitBias().ifPresent { it.validate() } + logprobs() + maxTokens() + metadata().ifPresent { it.validate() } + n() + numRetries() + parallelToolCalls() + presencePenalty() + responseFormat().ifPresent { it.validate() } + seed() + serviceTier() + stop().ifPresent { it.validate() } + stream() + streamOptions().ifPresent { it.validate() } + temperature() + toolChoice().ifPresent { it.validate() } + tools().ifPresent { it.forEach { it.validate() } } + topLogprobs() + topP() + user() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (messages.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (model.asKnown().isPresent) 1 else 0) + + (if (caching.asKnown().isPresent) 1 else 0) + + (contextWindowFallbackDict.asKnown().getOrNull()?.validity() ?: 0) + + (fallbacks.asKnown().getOrNull()?.size ?: 0) + + (if (frequencyPenalty.asKnown().isPresent) 1 else 0) + + (functionCall.asKnown().getOrNull()?.validity() ?: 0) + + (functions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (guardrails.asKnown().getOrNull()?.size ?: 0) + + (logitBias.asKnown().getOrNull()?.validity() ?: 0) + + (if (logprobs.asKnown().isPresent) 1 else 0) + + (if (maxTokens.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (n.asKnown().isPresent) 1 else 0) + + (if (numRetries.asKnown().isPresent) 1 else 0) + + (if (parallelToolCalls.asKnown().isPresent) 1 else 0) + + (if (presencePenalty.asKnown().isPresent) 1 else 0) + + (responseFormat.asKnown().getOrNull()?.validity() ?: 0) + + (if (seed.asKnown().isPresent) 1 else 0) + + (if (serviceTier.asKnown().isPresent) 1 else 0) + + (stop.asKnown().getOrNull()?.validity() ?: 0) + + (if (stream.asKnown().isPresent) 1 else 0) + + (streamOptions.asKnown().getOrNull()?.validity() ?: 0) + + (if (temperature.asKnown().isPresent) 1 else 0) + + (toolChoice.asKnown().getOrNull()?.validity() ?: 0) + + (tools.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (topLogprobs.asKnown().isPresent) 1 else 0) + + (if (topP.asKnown().isPresent) 1 else 0) + + (if (user.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + messages == other.messages && + model == other.model && + caching == other.caching && + contextWindowFallbackDict == other.contextWindowFallbackDict && + fallbacks == other.fallbacks && + frequencyPenalty == other.frequencyPenalty && + functionCall == other.functionCall && + functions == other.functions && + guardrails == other.guardrails && + logitBias == other.logitBias && + logprobs == other.logprobs && + maxTokens == other.maxTokens && + metadata == other.metadata && + n == other.n && + numRetries == other.numRetries && + parallelToolCalls == other.parallelToolCalls && + presencePenalty == other.presencePenalty && + responseFormat == other.responseFormat && + seed == other.seed && + serviceTier == other.serviceTier && + stop == other.stop && + stream == other.stream && + streamOptions == other.streamOptions && + temperature == other.temperature && + toolChoice == other.toolChoice && + tools == other.tools && + topLogprobs == other.topLogprobs && + topP == other.topP && + user == other.user && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + messages, + model, + caching, + contextWindowFallbackDict, + fallbacks, + frequencyPenalty, + functionCall, + functions, + guardrails, + logitBias, + logprobs, + maxTokens, + metadata, + n, + numRetries, + parallelToolCalls, + presencePenalty, + responseFormat, + seed, + serviceTier, + stop, + stream, + streamOptions, + temperature, + toolChoice, + tools, + topLogprobs, + topP, + user, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{messages=$messages, model=$model, caching=$caching, contextWindowFallbackDict=$contextWindowFallbackDict, fallbacks=$fallbacks, frequencyPenalty=$frequencyPenalty, functionCall=$functionCall, functions=$functions, guardrails=$guardrails, logitBias=$logitBias, logprobs=$logprobs, maxTokens=$maxTokens, metadata=$metadata, n=$n, numRetries=$numRetries, parallelToolCalls=$parallelToolCalls, presencePenalty=$presencePenalty, responseFormat=$responseFormat, seed=$seed, serviceTier=$serviceTier, stop=$stop, stream=$stream, streamOptions=$streamOptions, temperature=$temperature, toolChoice=$toolChoice, tools=$tools, topLogprobs=$topLogprobs, topP=$topP, user=$user, additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = Message.Deserializer::class) + @JsonSerialize(using = Message.Serializer::class) + class Message + private constructor( + private val chatCompletionUser: ChatCompletionUserMessage? = null, + private val chatCompletionAssistant: ChatCompletionAssistantMessage? = null, + private val chatCompletionTool: ChatCompletionToolMessage? = null, + private val chatCompletionSystem: ChatCompletionSystemMessage? = null, + private val chatCompletionFunction: ChatCompletionFunctionMessage? = null, + private val chatCompletionDeveloper: ChatCompletionDeveloperMessage? = null, + private val _json: JsonValue? = null, + ) { + + fun chatCompletionUser(): Optional = + Optional.ofNullable(chatCompletionUser) + + fun chatCompletionAssistant(): Optional = + Optional.ofNullable(chatCompletionAssistant) + + fun chatCompletionTool(): Optional = + Optional.ofNullable(chatCompletionTool) + + fun chatCompletionSystem(): Optional = + Optional.ofNullable(chatCompletionSystem) + + fun chatCompletionFunction(): Optional = + Optional.ofNullable(chatCompletionFunction) + + fun chatCompletionDeveloper(): Optional = + Optional.ofNullable(chatCompletionDeveloper) + + fun isChatCompletionUser(): Boolean = chatCompletionUser != null + + fun isChatCompletionAssistant(): Boolean = chatCompletionAssistant != null + + fun isChatCompletionTool(): Boolean = chatCompletionTool != null + + fun isChatCompletionSystem(): Boolean = chatCompletionSystem != null + + fun isChatCompletionFunction(): Boolean = chatCompletionFunction != null + + fun isChatCompletionDeveloper(): Boolean = chatCompletionDeveloper != null + + fun asChatCompletionUser(): ChatCompletionUserMessage = + chatCompletionUser.getOrThrow("chatCompletionUser") + + fun asChatCompletionAssistant(): ChatCompletionAssistantMessage = + chatCompletionAssistant.getOrThrow("chatCompletionAssistant") + + fun asChatCompletionTool(): ChatCompletionToolMessage = + chatCompletionTool.getOrThrow("chatCompletionTool") + + fun asChatCompletionSystem(): ChatCompletionSystemMessage = + chatCompletionSystem.getOrThrow("chatCompletionSystem") + + fun asChatCompletionFunction(): ChatCompletionFunctionMessage = + chatCompletionFunction.getOrThrow("chatCompletionFunction") + + fun asChatCompletionDeveloper(): ChatCompletionDeveloperMessage = + chatCompletionDeveloper.getOrThrow("chatCompletionDeveloper") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + chatCompletionUser != null -> visitor.visitChatCompletionUser(chatCompletionUser) + chatCompletionAssistant != null -> + visitor.visitChatCompletionAssistant(chatCompletionAssistant) + chatCompletionTool != null -> visitor.visitChatCompletionTool(chatCompletionTool) + chatCompletionSystem != null -> + visitor.visitChatCompletionSystem(chatCompletionSystem) + chatCompletionFunction != null -> + visitor.visitChatCompletionFunction(chatCompletionFunction) + chatCompletionDeveloper != null -> + visitor.visitChatCompletionDeveloper(chatCompletionDeveloper) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Message = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitChatCompletionUser( + chatCompletionUser: ChatCompletionUserMessage + ) { + chatCompletionUser.validate() + } + + override fun visitChatCompletionAssistant( + chatCompletionAssistant: ChatCompletionAssistantMessage + ) { + chatCompletionAssistant.validate() + } + + override fun visitChatCompletionTool( + chatCompletionTool: ChatCompletionToolMessage + ) { + chatCompletionTool.validate() + } + + override fun visitChatCompletionSystem( + chatCompletionSystem: ChatCompletionSystemMessage + ) { + chatCompletionSystem.validate() + } + + override fun visitChatCompletionFunction( + chatCompletionFunction: ChatCompletionFunctionMessage + ) { + chatCompletionFunction.validate() + } + + override fun visitChatCompletionDeveloper( + chatCompletionDeveloper: ChatCompletionDeveloperMessage + ) { + chatCompletionDeveloper.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitChatCompletionUser( + chatCompletionUser: ChatCompletionUserMessage + ) = chatCompletionUser.validity() + + override fun visitChatCompletionAssistant( + chatCompletionAssistant: ChatCompletionAssistantMessage + ) = chatCompletionAssistant.validity() + + override fun visitChatCompletionTool( + chatCompletionTool: ChatCompletionToolMessage + ) = chatCompletionTool.validity() + + override fun visitChatCompletionSystem( + chatCompletionSystem: ChatCompletionSystemMessage + ) = chatCompletionSystem.validity() + + override fun visitChatCompletionFunction( + chatCompletionFunction: ChatCompletionFunctionMessage + ) = chatCompletionFunction.validity() + + override fun visitChatCompletionDeveloper( + chatCompletionDeveloper: ChatCompletionDeveloperMessage + ) = chatCompletionDeveloper.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Message && + chatCompletionUser == other.chatCompletionUser && + chatCompletionAssistant == other.chatCompletionAssistant && + chatCompletionTool == other.chatCompletionTool && + chatCompletionSystem == other.chatCompletionSystem && + chatCompletionFunction == other.chatCompletionFunction && + chatCompletionDeveloper == other.chatCompletionDeveloper + } + + override fun hashCode(): Int = + Objects.hash( + chatCompletionUser, + chatCompletionAssistant, + chatCompletionTool, + chatCompletionSystem, + chatCompletionFunction, + chatCompletionDeveloper, + ) + + override fun toString(): String = + when { + chatCompletionUser != null -> "Message{chatCompletionUser=$chatCompletionUser}" + chatCompletionAssistant != null -> + "Message{chatCompletionAssistant=$chatCompletionAssistant}" + chatCompletionTool != null -> "Message{chatCompletionTool=$chatCompletionTool}" + chatCompletionSystem != null -> + "Message{chatCompletionSystem=$chatCompletionSystem}" + chatCompletionFunction != null -> + "Message{chatCompletionFunction=$chatCompletionFunction}" + chatCompletionDeveloper != null -> + "Message{chatCompletionDeveloper=$chatCompletionDeveloper}" + _json != null -> "Message{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Message") + } + + companion object { + + @JvmStatic + fun ofChatCompletionUser(chatCompletionUser: ChatCompletionUserMessage) = + Message(chatCompletionUser = chatCompletionUser) + + @JvmStatic + fun ofChatCompletionAssistant(chatCompletionAssistant: ChatCompletionAssistantMessage) = + Message(chatCompletionAssistant = chatCompletionAssistant) + + @JvmStatic + fun ofChatCompletionTool(chatCompletionTool: ChatCompletionToolMessage) = + Message(chatCompletionTool = chatCompletionTool) + + @JvmStatic + fun ofChatCompletionSystem(chatCompletionSystem: ChatCompletionSystemMessage) = + Message(chatCompletionSystem = chatCompletionSystem) + + @JvmStatic + fun ofChatCompletionFunction(chatCompletionFunction: ChatCompletionFunctionMessage) = + Message(chatCompletionFunction = chatCompletionFunction) + + @JvmStatic + fun ofChatCompletionDeveloper(chatCompletionDeveloper: ChatCompletionDeveloperMessage) = + Message(chatCompletionDeveloper = chatCompletionDeveloper) + } + + /** + * An interface that defines how to map each variant of [Message] to a value of type [T]. + */ + interface Visitor { + + fun visitChatCompletionUser(chatCompletionUser: ChatCompletionUserMessage): T + + fun visitChatCompletionAssistant( + chatCompletionAssistant: ChatCompletionAssistantMessage + ): T + + fun visitChatCompletionTool(chatCompletionTool: ChatCompletionToolMessage): T + + fun visitChatCompletionSystem(chatCompletionSystem: ChatCompletionSystemMessage): T + + fun visitChatCompletionFunction( + chatCompletionFunction: ChatCompletionFunctionMessage + ): T + + fun visitChatCompletionDeveloper( + chatCompletionDeveloper: ChatCompletionDeveloperMessage + ): T + + /** + * Maps an unknown variant of [Message] to a value of type [T]. + * + * An instance of [Message] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Message: $json") + } + } + + internal class Deserializer : BaseDeserializer(Message::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Message { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Message(chatCompletionUser = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { Message(chatCompletionAssistant = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(chatCompletionTool = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { Message(chatCompletionSystem = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { Message(chatCompletionFunction = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { Message(chatCompletionDeveloper = it, _json = json) }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> Message(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Message::class) { + + override fun serialize( + value: Message, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.chatCompletionUser != null -> + generator.writeObject(value.chatCompletionUser) + value.chatCompletionAssistant != null -> + generator.writeObject(value.chatCompletionAssistant) + value.chatCompletionTool != null -> + generator.writeObject(value.chatCompletionTool) + value.chatCompletionSystem != null -> + generator.writeObject(value.chatCompletionSystem) + value.chatCompletionFunction != null -> + generator.writeObject(value.chatCompletionFunction) + value.chatCompletionDeveloper != null -> + generator.writeObject(value.chatCompletionDeveloper) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Message") + } + } + } + + class ChatCompletionUserMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val content: JsonField, + private val role: JsonValue, + private val cacheControl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + ) : this(content, role, cacheControl, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun content(): Content = content.getRequired("content") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("user") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun cacheControl(): Optional = cacheControl.getOptional("cache_control") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionUserMessage]. + * + * The following fields are required: + * ```java + * .content() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionUserMessage]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var role: JsonValue = JsonValue.from("user") + private var cacheControl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionUserMessage: ChatCompletionUserMessage) = apply { + content = chatCompletionUserMessage.content + role = chatCompletionUserMessage.role + cacheControl = chatCompletionUserMessage.cacheControl + additionalProperties = + chatCompletionUserMessage.additionalProperties.toMutableMap() + } + + fun content(content: Content) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** + * Alias for calling [content] with + * `Content.ofUnnamedSchemaWithArrayParent4s(unnamedSchemaWithArrayParent4s)`. + */ + fun contentOfUnnamedSchemaWithArrayParent4s( + unnamedSchemaWithArrayParent4s: List + ) = + content( + Content.ofUnnamedSchemaWithArrayParent4s(unnamedSchemaWithArrayParent4s) + ) + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("user") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed [CacheControl] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionUserMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionUserMessage = + ChatCompletionUserMessage( + checkRequired("content", content), + role, + cacheControl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionUserMessage = apply { + if (validated) { + return@apply + } + + content().validate() + _role().let { + if (it != JsonValue.from("user")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (content.asKnown().getOrNull()?.validity() ?: 0) + + role.let { if (it == JsonValue.from("user")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val unnamedSchemaWithArrayParent4s: List? = + null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun unnamedSchemaWithArrayParent4s(): + Optional> = + Optional.ofNullable(unnamedSchemaWithArrayParent4s) + + fun isString(): Boolean = string != null + + fun isUnnamedSchemaWithArrayParent4s(): Boolean = + unnamedSchemaWithArrayParent4s != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnnamedSchemaWithArrayParent4s(): List = + unnamedSchemaWithArrayParent4s.getOrThrow("unnamedSchemaWithArrayParent4s") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + unnamedSchemaWithArrayParent4s != null -> + visitor.visitUnnamedSchemaWithArrayParent4s( + unnamedSchemaWithArrayParent4s + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitUnnamedSchemaWithArrayParent4s( + unnamedSchemaWithArrayParent4s: List + ) { + unnamedSchemaWithArrayParent4s.forEach { it.validate() } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitUnnamedSchemaWithArrayParent4s( + unnamedSchemaWithArrayParent4s: List + ) = unnamedSchemaWithArrayParent4s.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + unnamedSchemaWithArrayParent4s == other.unnamedSchemaWithArrayParent4s + } + + override fun hashCode(): Int = Objects.hash(string, unnamedSchemaWithArrayParent4s) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + unnamedSchemaWithArrayParent4s != null -> + "Content{unnamedSchemaWithArrayParent4s=$unnamedSchemaWithArrayParent4s}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofUnnamedSchemaWithArrayParent4s( + unnamedSchemaWithArrayParent4s: List + ) = + Content( + unnamedSchemaWithArrayParent4s = + unnamedSchemaWithArrayParent4s.toImmutable() + ) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitUnnamedSchemaWithArrayParent4s( + unnamedSchemaWithArrayParent4s: List + ): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { + Content( + unnamedSchemaWithArrayParent4s = it, + _json = json, + ) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unnamedSchemaWithArrayParent4s != null -> + generator.writeObject(value.unnamedSchemaWithArrayParent4s) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + + @JsonDeserialize(using = UnnamedSchemaWithArrayParent4.Deserializer::class) + @JsonSerialize(using = UnnamedSchemaWithArrayParent4.Serializer::class) + class UnnamedSchemaWithArrayParent4 + private constructor( + private val chatCompletionTextObject: ChatCompletionTextObject? = null, + private val chatCompletionImageObject: ChatCompletionImageObject? = null, + private val chatCompletionAudioObject: ChatCompletionAudioObject? = null, + private val chatCompletionDocumentObject: ChatCompletionDocumentObject? = null, + private val chatCompletionVideoObject: ChatCompletionVideoObject? = null, + private val chatCompletionFileObject: ChatCompletionFileObject? = null, + private val _json: JsonValue? = null, + ) { + + fun chatCompletionTextObject(): Optional = + Optional.ofNullable(chatCompletionTextObject) + + fun chatCompletionImageObject(): Optional = + Optional.ofNullable(chatCompletionImageObject) + + fun chatCompletionAudioObject(): Optional = + Optional.ofNullable(chatCompletionAudioObject) + + fun chatCompletionDocumentObject(): Optional = + Optional.ofNullable(chatCompletionDocumentObject) + + fun chatCompletionVideoObject(): Optional = + Optional.ofNullable(chatCompletionVideoObject) + + fun chatCompletionFileObject(): Optional = + Optional.ofNullable(chatCompletionFileObject) + + fun isChatCompletionTextObject(): Boolean = chatCompletionTextObject != null + + fun isChatCompletionImageObject(): Boolean = chatCompletionImageObject != null + + fun isChatCompletionAudioObject(): Boolean = chatCompletionAudioObject != null + + fun isChatCompletionDocumentObject(): Boolean = + chatCompletionDocumentObject != null + + fun isChatCompletionVideoObject(): Boolean = chatCompletionVideoObject != null + + fun isChatCompletionFileObject(): Boolean = chatCompletionFileObject != null + + fun asChatCompletionTextObject(): ChatCompletionTextObject = + chatCompletionTextObject.getOrThrow("chatCompletionTextObject") + + fun asChatCompletionImageObject(): ChatCompletionImageObject = + chatCompletionImageObject.getOrThrow("chatCompletionImageObject") + + fun asChatCompletionAudioObject(): ChatCompletionAudioObject = + chatCompletionAudioObject.getOrThrow("chatCompletionAudioObject") + + fun asChatCompletionDocumentObject(): ChatCompletionDocumentObject = + chatCompletionDocumentObject.getOrThrow("chatCompletionDocumentObject") + + fun asChatCompletionVideoObject(): ChatCompletionVideoObject = + chatCompletionVideoObject.getOrThrow("chatCompletionVideoObject") + + fun asChatCompletionFileObject(): ChatCompletionFileObject = + chatCompletionFileObject.getOrThrow("chatCompletionFileObject") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + chatCompletionTextObject != null -> + visitor.visitChatCompletionTextObject(chatCompletionTextObject) + chatCompletionImageObject != null -> + visitor.visitChatCompletionImageObject(chatCompletionImageObject) + chatCompletionAudioObject != null -> + visitor.visitChatCompletionAudioObject(chatCompletionAudioObject) + chatCompletionDocumentObject != null -> + visitor.visitChatCompletionDocumentObject( + chatCompletionDocumentObject + ) + chatCompletionVideoObject != null -> + visitor.visitChatCompletionVideoObject(chatCompletionVideoObject) + chatCompletionFileObject != null -> + visitor.visitChatCompletionFileObject(chatCompletionFileObject) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnnamedSchemaWithArrayParent4 = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) { + chatCompletionTextObject.validate() + } + + override fun visitChatCompletionImageObject( + chatCompletionImageObject: ChatCompletionImageObject + ) { + chatCompletionImageObject.validate() + } + + override fun visitChatCompletionAudioObject( + chatCompletionAudioObject: ChatCompletionAudioObject + ) { + chatCompletionAudioObject.validate() + } + + override fun visitChatCompletionDocumentObject( + chatCompletionDocumentObject: ChatCompletionDocumentObject + ) { + chatCompletionDocumentObject.validate() + } + + override fun visitChatCompletionVideoObject( + chatCompletionVideoObject: ChatCompletionVideoObject + ) { + chatCompletionVideoObject.validate() + } + + override fun visitChatCompletionFileObject( + chatCompletionFileObject: ChatCompletionFileObject + ) { + chatCompletionFileObject.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) = chatCompletionTextObject.validity() + + override fun visitChatCompletionImageObject( + chatCompletionImageObject: ChatCompletionImageObject + ) = chatCompletionImageObject.validity() + + override fun visitChatCompletionAudioObject( + chatCompletionAudioObject: ChatCompletionAudioObject + ) = chatCompletionAudioObject.validity() + + override fun visitChatCompletionDocumentObject( + chatCompletionDocumentObject: ChatCompletionDocumentObject + ) = chatCompletionDocumentObject.validity() + + override fun visitChatCompletionVideoObject( + chatCompletionVideoObject: ChatCompletionVideoObject + ) = chatCompletionVideoObject.validity() + + override fun visitChatCompletionFileObject( + chatCompletionFileObject: ChatCompletionFileObject + ) = chatCompletionFileObject.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnnamedSchemaWithArrayParent4 && + chatCompletionTextObject == other.chatCompletionTextObject && + chatCompletionImageObject == other.chatCompletionImageObject && + chatCompletionAudioObject == other.chatCompletionAudioObject && + chatCompletionDocumentObject == other.chatCompletionDocumentObject && + chatCompletionVideoObject == other.chatCompletionVideoObject && + chatCompletionFileObject == other.chatCompletionFileObject + } + + override fun hashCode(): Int = + Objects.hash( + chatCompletionTextObject, + chatCompletionImageObject, + chatCompletionAudioObject, + chatCompletionDocumentObject, + chatCompletionVideoObject, + chatCompletionFileObject, + ) + + override fun toString(): String = + when { + chatCompletionTextObject != null -> + "UnnamedSchemaWithArrayParent4{chatCompletionTextObject=$chatCompletionTextObject}" + chatCompletionImageObject != null -> + "UnnamedSchemaWithArrayParent4{chatCompletionImageObject=$chatCompletionImageObject}" + chatCompletionAudioObject != null -> + "UnnamedSchemaWithArrayParent4{chatCompletionAudioObject=$chatCompletionAudioObject}" + chatCompletionDocumentObject != null -> + "UnnamedSchemaWithArrayParent4{chatCompletionDocumentObject=$chatCompletionDocumentObject}" + chatCompletionVideoObject != null -> + "UnnamedSchemaWithArrayParent4{chatCompletionVideoObject=$chatCompletionVideoObject}" + chatCompletionFileObject != null -> + "UnnamedSchemaWithArrayParent4{chatCompletionFileObject=$chatCompletionFileObject}" + _json != null -> "UnnamedSchemaWithArrayParent4{_unknown=$_json}" + else -> + throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent4") + } + + companion object { + + @JvmStatic + fun ofChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) = + UnnamedSchemaWithArrayParent4( + chatCompletionTextObject = chatCompletionTextObject + ) + + @JvmStatic + fun ofChatCompletionImageObject( + chatCompletionImageObject: ChatCompletionImageObject + ) = + UnnamedSchemaWithArrayParent4( + chatCompletionImageObject = chatCompletionImageObject + ) + + @JvmStatic + fun ofChatCompletionAudioObject( + chatCompletionAudioObject: ChatCompletionAudioObject + ) = + UnnamedSchemaWithArrayParent4( + chatCompletionAudioObject = chatCompletionAudioObject + ) + + @JvmStatic + fun ofChatCompletionDocumentObject( + chatCompletionDocumentObject: ChatCompletionDocumentObject + ) = + UnnamedSchemaWithArrayParent4( + chatCompletionDocumentObject = chatCompletionDocumentObject + ) + + @JvmStatic + fun ofChatCompletionVideoObject( + chatCompletionVideoObject: ChatCompletionVideoObject + ) = + UnnamedSchemaWithArrayParent4( + chatCompletionVideoObject = chatCompletionVideoObject + ) + + @JvmStatic + fun ofChatCompletionFileObject( + chatCompletionFileObject: ChatCompletionFileObject + ) = + UnnamedSchemaWithArrayParent4( + chatCompletionFileObject = chatCompletionFileObject + ) + } + + /** + * An interface that defines how to map each variant of + * [UnnamedSchemaWithArrayParent4] to a value of type [T]. + */ + interface Visitor { + + fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ): T + + fun visitChatCompletionImageObject( + chatCompletionImageObject: ChatCompletionImageObject + ): T + + fun visitChatCompletionAudioObject( + chatCompletionAudioObject: ChatCompletionAudioObject + ): T + + fun visitChatCompletionDocumentObject( + chatCompletionDocumentObject: ChatCompletionDocumentObject + ): T + + fun visitChatCompletionVideoObject( + chatCompletionVideoObject: ChatCompletionVideoObject + ): T + + fun visitChatCompletionFileObject( + chatCompletionFileObject: ChatCompletionFileObject + ): T + + /** + * Maps an unknown variant of [UnnamedSchemaWithArrayParent4] to a value of + * type [T]. + * + * An instance of [UnnamedSchemaWithArrayParent4] can contain an unknown + * variant if it was deserialized from data that doesn't match any known + * variant. For example, if the SDK is on an older version than the API, + * then the API may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException( + "Unknown UnnamedSchemaWithArrayParent4: $json" + ) + } + } + + internal class Deserializer : + BaseDeserializer( + UnnamedSchemaWithArrayParent4::class + ) { + + override fun ObjectCodec.deserialize( + node: JsonNode + ): UnnamedSchemaWithArrayParent4 { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent4( + chatCompletionTextObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent4( + chatCompletionImageObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent4( + chatCompletionAudioObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent4( + chatCompletionDocumentObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent4( + chatCompletionVideoObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent4( + chatCompletionFileObject = it, + _json = json, + ) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing + // from boolean). + 0 -> UnnamedSchemaWithArrayParent4(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then + // use the first completely valid match, or simply the first match + // if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer( + UnnamedSchemaWithArrayParent4::class + ) { + + override fun serialize( + value: UnnamedSchemaWithArrayParent4, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.chatCompletionTextObject != null -> + generator.writeObject(value.chatCompletionTextObject) + value.chatCompletionImageObject != null -> + generator.writeObject(value.chatCompletionImageObject) + value.chatCompletionAudioObject != null -> + generator.writeObject(value.chatCompletionAudioObject) + value.chatCompletionDocumentObject != null -> + generator.writeObject(value.chatCompletionDocumentObject) + value.chatCompletionVideoObject != null -> + generator.writeObject(value.chatCompletionVideoObject) + value.chatCompletionFileObject != null -> + generator.writeObject(value.chatCompletionFileObject) + value._json != null -> generator.writeObject(value._json) + else -> + throw IllegalStateException( + "Invalid UnnamedSchemaWithArrayParent4" + ) + } + } + } + + class ChatCompletionTextObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val text: JsonField, + private val type: JsonValue, + private val cacheControl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("text") + @ExcludeMissing + text: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + ) : this(text, type, cacheControl, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun text(): String = text.getRequired("text") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("text") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * Returns the raw JSON value of [text]. + * + * Unlike [text], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("text") @ExcludeMissing fun _text(): JsonField = text + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionTextObject]. + * + * The following fields are required: + * ```java + * .text() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionTextObject]. */ + class Builder internal constructor() { + + private var text: JsonField? = null + private var type: JsonValue = JsonValue.from("text") + private var cacheControl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionTextObject: ChatCompletionTextObject) = + apply { + text = chatCompletionTextObject.text + type = chatCompletionTextObject.type + cacheControl = chatCompletionTextObject.cacheControl + additionalProperties = + chatCompletionTextObject.additionalProperties.toMutableMap() + } + + fun text(text: String) = text(JsonField.of(text)) + + /** + * Sets [Builder.text] to an arbitrary JSON value. + * + * You should usually call [Builder.text] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun text(text: JsonField) = apply { this.text = text } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("text") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionTextObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .text() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionTextObject = + ChatCompletionTextObject( + checkRequired("text", text), + type, + cacheControl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionTextObject = apply { + if (validated) { + return@apply + } + + text() + _type().let { + if (it != JsonValue.from("text")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + cacheControl().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (text.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("text")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if + * the server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [CacheControl]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = + cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionTextObject && + text == other.text && + type == other.type && + cacheControl == other.cacheControl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(text, type, cacheControl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionTextObject{text=$text, type=$type, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" + } + + class ChatCompletionImageObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val imageUrl: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("image_url") + @ExcludeMissing + imageUrl: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + ) : this(imageUrl, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun imageUrl(): ImageUrl = imageUrl.getRequired("image_url") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("image_url") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [imageUrl]. + * + * Unlike [imageUrl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("image_url") + @ExcludeMissing + fun _imageUrl(): JsonField = imageUrl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionImageObject]. + * + * The following fields are required: + * ```java + * .imageUrl() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionImageObject]. */ + class Builder internal constructor() { + + private var imageUrl: JsonField? = null + private var type: JsonValue = JsonValue.from("image_url") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionImageObject: ChatCompletionImageObject + ) = apply { + imageUrl = chatCompletionImageObject.imageUrl + type = chatCompletionImageObject.type + additionalProperties = + chatCompletionImageObject.additionalProperties.toMutableMap() + } + + fun imageUrl(imageUrl: ImageUrl) = imageUrl(JsonField.of(imageUrl)) + + /** + * Sets [Builder.imageUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.imageUrl] with a well-typed + * [ImageUrl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun imageUrl(imageUrl: JsonField) = apply { + this.imageUrl = imageUrl + } + + /** Alias for calling [imageUrl] with `ImageUrl.ofString(string)`. */ + fun imageUrl(string: String) = imageUrl(ImageUrl.ofString(string)) + + /** + * Alias for calling [imageUrl] with + * `ImageUrl.ofChatCompletionImageUrlObject(chatCompletionImageUrlObject)`. + */ + fun imageUrl( + chatCompletionImageUrlObject: ImageUrl.ChatCompletionImageUrlObject + ) = + imageUrl( + ImageUrl.ofChatCompletionImageUrlObject( + chatCompletionImageUrlObject + ) + ) + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("image_url") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionImageObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .imageUrl() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionImageObject = + ChatCompletionImageObject( + checkRequired("imageUrl", imageUrl), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionImageObject = apply { + if (validated) { + return@apply + } + + imageUrl().validate() + _type().let { + if (it != JsonValue.from("image_url")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (imageUrl.asKnown().getOrNull()?.validity() ?: 0) + + type.let { if (it == JsonValue.from("image_url")) 1 else 0 } + + @JsonDeserialize(using = ImageUrl.Deserializer::class) + @JsonSerialize(using = ImageUrl.Serializer::class) + class ImageUrl + private constructor( + private val string: String? = null, + private val chatCompletionImageUrlObject: + ChatCompletionImageUrlObject? = + null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun chatCompletionImageUrlObject(): + Optional = + Optional.ofNullable(chatCompletionImageUrlObject) + + fun isString(): Boolean = string != null + + fun isChatCompletionImageUrlObject(): Boolean = + chatCompletionImageUrlObject != null + + fun asString(): String = string.getOrThrow("string") + + fun asChatCompletionImageUrlObject(): ChatCompletionImageUrlObject = + chatCompletionImageUrlObject.getOrThrow( + "chatCompletionImageUrlObject" + ) + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + chatCompletionImageUrlObject != null -> + visitor.visitChatCompletionImageUrlObject( + chatCompletionImageUrlObject + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): ImageUrl = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitChatCompletionImageUrlObject( + chatCompletionImageUrlObject: + ChatCompletionImageUrlObject + ) { + chatCompletionImageUrlObject.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitChatCompletionImageUrlObject( + chatCompletionImageUrlObject: + ChatCompletionImageUrlObject + ) = chatCompletionImageUrlObject.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ImageUrl && + string == other.string && + chatCompletionImageUrlObject == + other.chatCompletionImageUrlObject + } + + override fun hashCode(): Int = + Objects.hash(string, chatCompletionImageUrlObject) + + override fun toString(): String = + when { + string != null -> "ImageUrl{string=$string}" + chatCompletionImageUrlObject != null -> + "ImageUrl{chatCompletionImageUrlObject=$chatCompletionImageUrlObject}" + _json != null -> "ImageUrl{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ImageUrl") + } + + companion object { + + @JvmStatic fun ofString(string: String) = ImageUrl(string = string) + + @JvmStatic + fun ofChatCompletionImageUrlObject( + chatCompletionImageUrlObject: ChatCompletionImageUrlObject + ) = + ImageUrl( + chatCompletionImageUrlObject = chatCompletionImageUrlObject + ) + } + + /** + * An interface that defines how to map each variant of [ImageUrl] to a + * value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitChatCompletionImageUrlObject( + chatCompletionImageUrlObject: ChatCompletionImageUrlObject + ): T + + /** + * Maps an unknown variant of [ImageUrl] to a value of type [T]. + * + * An instance of [ImageUrl] can contain an unknown variant if it + * was deserialized from data that doesn't match any known variant. + * For example, if the SDK is on an older version than the API, then + * the API may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown ImageUrl: $json") + } + } + + internal class Deserializer : + BaseDeserializer(ImageUrl::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): ImageUrl { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef< + ChatCompletionImageUrlObject + >(), + ) + ?.let { + ImageUrl( + chatCompletionImageUrlObject = it, + _json = json, + ) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { ImageUrl(string = it, _json = json) }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. + // deserializing from boolean). + 0 -> ImageUrl(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, + // then use the first completely valid match, or simply the + // first match if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } + ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(ImageUrl::class) { + + override fun serialize( + value: ImageUrl, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.chatCompletionImageUrlObject != null -> + generator.writeObject( + value.chatCompletionImageUrlObject + ) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid ImageUrl") + } + } + } + + class ChatCompletionImageUrlObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val url: JsonField, + private val detail: JsonField, + private val format: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") + @ExcludeMissing + url: JsonField = JsonMissing.of(), + @JsonProperty("detail") + @ExcludeMissing + detail: JsonField = JsonMissing.of(), + @JsonProperty("format") + @ExcludeMissing + format: JsonField = JsonMissing.of(), + ) : this(url, detail, format, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an + * unexpected type or is unexpectedly missing or null (e.g. if the + * server responded with an unexpected value). + */ + fun url(): String = url.getRequired("url") + + /** + * @throws HanzoInvalidDataException if the JSON field has an + * unexpected type (e.g. if the server responded with an + * unexpected value). + */ + fun detail(): Optional = detail.getOptional("detail") + + /** + * @throws HanzoInvalidDataException if the JSON field has an + * unexpected type (e.g. if the server responded with an + * unexpected value). + */ + fun format(): Optional = format.getOptional("format") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("url") + @ExcludeMissing + fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [detail]. + * + * Unlike [detail], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("detail") + @ExcludeMissing + fun _detail(): JsonField = detail + + /** + * Returns the raw JSON value of [format]. + * + * Unlike [format], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("format") + @ExcludeMissing + fun _format(): JsonField = format + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionImageUrlObject]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionImageUrlObject]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var detail: JsonField = JsonMissing.of() + private var format: JsonField = JsonMissing.of() + private var additionalProperties: + MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionImageUrlObject: ChatCompletionImageUrlObject + ) = apply { + url = chatCompletionImageUrlObject.url + detail = chatCompletionImageUrlObject.detail + format = chatCompletionImageUrlObject.format + additionalProperties = + chatCompletionImageUrlObject.additionalProperties + .toMutableMap() + } + + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed + * [String] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun detail(detail: String) = detail(JsonField.of(detail)) + + /** + * Sets [Builder.detail] to an arbitrary JSON value. + * + * You should usually call [Builder.detail] with a well-typed + * [String] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun detail(detail: JsonField) = apply { + this.detail = detail + } + + fun format(format: String) = format(JsonField.of(format)) + + /** + * Sets [Builder.format] to an arbitrary JSON value. + * + * You should usually call [Builder.format] with a well-typed + * [String] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun format(format: JsonField) = apply { + this.format = format + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = + apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of + * [ChatCompletionImageUrlObject]. + * + * Further updates to this [Builder] will not mutate the + * returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionImageUrlObject = + ChatCompletionImageUrlObject( + checkRequired("url", url), + detail, + format, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionImageUrlObject = apply { + if (validated) { + return@apply + } + + url() + detail() + format() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (url.asKnown().isPresent) 1 else 0) + + (if (detail.asKnown().isPresent) 1 else 0) + + (if (format.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionImageUrlObject && + url == other.url && + detail == other.detail && + format == other.format && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(url, detail, format, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionImageUrlObject{url=$url, detail=$detail, format=$format, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionImageObject && + imageUrl == other.imageUrl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(imageUrl, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionImageObject{imageUrl=$imageUrl, type=$type, additionalProperties=$additionalProperties}" + } + + class ChatCompletionAudioObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val inputAudio: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("input_audio") + @ExcludeMissing + inputAudio: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + ) : this(inputAudio, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun inputAudio(): InputAudio = inputAudio.getRequired("input_audio") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("input_audio") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [inputAudio]. + * + * Unlike [inputAudio], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("input_audio") + @ExcludeMissing + fun _inputAudio(): JsonField = inputAudio + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionAudioObject]. + * + * The following fields are required: + * ```java + * .inputAudio() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionAudioObject]. */ + class Builder internal constructor() { + + private var inputAudio: JsonField? = null + private var type: JsonValue = JsonValue.from("input_audio") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionAudioObject: ChatCompletionAudioObject + ) = apply { + inputAudio = chatCompletionAudioObject.inputAudio + type = chatCompletionAudioObject.type + additionalProperties = + chatCompletionAudioObject.additionalProperties.toMutableMap() + } + + fun inputAudio(inputAudio: InputAudio) = + inputAudio(JsonField.of(inputAudio)) + + /** + * Sets [Builder.inputAudio] to an arbitrary JSON value. + * + * You should usually call [Builder.inputAudio] with a well-typed + * [InputAudio] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun inputAudio(inputAudio: JsonField) = apply { + this.inputAudio = inputAudio + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("input_audio") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionAudioObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .inputAudio() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionAudioObject = + ChatCompletionAudioObject( + checkRequired("inputAudio", inputAudio), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionAudioObject = apply { + if (validated) { + return@apply + } + + inputAudio().validate() + _type().let { + if (it != JsonValue.from("input_audio")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (inputAudio.asKnown().getOrNull()?.validity() ?: 0) + + type.let { if (it == JsonValue.from("input_audio")) 1 else 0 } + + class InputAudio + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val data: JsonField, + private val format: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("data") + @ExcludeMissing + data: JsonField = JsonMissing.of(), + @JsonProperty("format") + @ExcludeMissing + format: JsonField = JsonMissing.of(), + ) : this(data, format, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server + * responded with an unexpected value). + */ + fun data(): String = data.getRequired("data") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server + * responded with an unexpected value). + */ + fun format(): Format = format.getRequired("format") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("data") + @ExcludeMissing + fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [format]. + * + * Unlike [format], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("format") + @ExcludeMissing + fun _format(): JsonField = format + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [InputAudio]. + * + * The following fields are required: + * ```java + * .data() + * .format() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InputAudio]. */ + class Builder internal constructor() { + + private var data: JsonField? = null + private var format: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(inputAudio: InputAudio) = apply { + data = inputAudio.data + format = inputAudio.format + additionalProperties = + inputAudio.additionalProperties.toMutableMap() + } + + fun data(data: String) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] + * value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + fun format(format: Format) = format(JsonField.of(format)) + + /** + * Sets [Builder.format] to an arbitrary JSON value. + * + * You should usually call [Builder.format] with a well-typed + * [Format] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun format(format: JsonField) = apply { + this.format = format + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InputAudio]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .data() + * .format() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InputAudio = + InputAudio( + checkRequired("data", data), + checkRequired("format", format), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): InputAudio = apply { + if (validated) { + return@apply + } + + data() + format().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (format.asKnown().getOrNull()?.validity() ?: 0) + + class Format + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized + * from data that doesn't match any known member, and you want to + * know that value. For example, if the SDK is on an older version + * than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val WAV = of("wav") + + @JvmField val MP3 = of("mp3") + + @JvmStatic fun of(value: String) = Format(JsonField.of(value)) + } + + /** An enum containing [Format]'s known values. */ + enum class Known { + WAV, + MP3, + } + + /** + * An enum containing [Format]'s known values, as well as an + * [_UNKNOWN] member. + * + * An instance of [Format] can contain an unknown value in a couple + * of cases: + * - It was deserialized from data that doesn't match any known + * member. For example, if the SDK is on an older version than the + * API, then the API may respond with new members that the SDK is + * unaware of. + * - It was constructed with an arbitrary value using the [of] + * method. + */ + enum class Value { + WAV, + MP3, + /** + * An enum member indicating that [Format] was instantiated with + * an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's + * value, or [Value._UNKNOWN] if the class was instantiated with an + * unknown value. + * + * Use the [known] method instead if you're certain the value is + * always known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + WAV -> Value.WAV + MP3 -> Value.MP3 + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's + * value. + * + * Use the [value] method instead if you're uncertain the value is + * always known and don't want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value + * is a not a known member. + */ + fun known(): Known = + when (this) { + WAV -> Known.WAV + MP3 -> Known.MP3 + else -> + throw HanzoInvalidDataException( + "Unknown Format: $value" + ) + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is + * primarily for debugging and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + HanzoInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Format = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Format && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InputAudio && + data == other.data && + format == other.format && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(data, format, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InputAudio{data=$data, format=$format, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionAudioObject && + inputAudio == other.inputAudio && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(inputAudio, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionAudioObject{inputAudio=$inputAudio, type=$type, additionalProperties=$additionalProperties}" + } + + class ChatCompletionDocumentObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val citations: JsonField, + private val context: JsonField, + private val source: JsonField, + private val title: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("citations") + @ExcludeMissing + citations: JsonField = JsonMissing.of(), + @JsonProperty("context") + @ExcludeMissing + context: JsonField = JsonMissing.of(), + @JsonProperty("source") + @ExcludeMissing + source: JsonField = JsonMissing.of(), + @JsonProperty("title") + @ExcludeMissing + title: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + ) : this(citations, context, source, title, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun citations(): Optional = citations.getOptional("citations") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun context(): String = context.getRequired("context") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun source(): Source = source.getRequired("source") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun title(): String = title.getRequired("title") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("document") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [citations]. + * + * Unlike [citations], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("citations") + @ExcludeMissing + fun _citations(): JsonField = citations + + /** + * Returns the raw JSON value of [context]. + * + * Unlike [context], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("context") + @ExcludeMissing + fun _context(): JsonField = context + + /** + * Returns the raw JSON value of [source]. + * + * Unlike [source], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("source") + @ExcludeMissing + fun _source(): JsonField = source + + /** + * Returns the raw JSON value of [title]. + * + * Unlike [title], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("title") + @ExcludeMissing + fun _title(): JsonField = title + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionDocumentObject]. + * + * The following fields are required: + * ```java + * .citations() + * .context() + * .source() + * .title() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionDocumentObject]. */ + class Builder internal constructor() { + + private var citations: JsonField? = null + private var context: JsonField? = null + private var source: JsonField? = null + private var title: JsonField? = null + private var type: JsonValue = JsonValue.from("document") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionDocumentObject: ChatCompletionDocumentObject + ) = apply { + citations = chatCompletionDocumentObject.citations + context = chatCompletionDocumentObject.context + source = chatCompletionDocumentObject.source + title = chatCompletionDocumentObject.title + type = chatCompletionDocumentObject.type + additionalProperties = + chatCompletionDocumentObject.additionalProperties.toMutableMap() + } + + fun citations(citations: Citations?) = + citations(JsonField.ofNullable(citations)) + + /** + * Alias for calling [Builder.citations] with `citations.orElse(null)`. + */ + fun citations(citations: Optional) = + citations(citations.getOrNull()) + + /** + * Sets [Builder.citations] to an arbitrary JSON value. + * + * You should usually call [Builder.citations] with a well-typed + * [Citations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun citations(citations: JsonField) = apply { + this.citations = citations + } + + fun context(context: String) = context(JsonField.of(context)) + + /** + * Sets [Builder.context] to an arbitrary JSON value. + * + * You should usually call [Builder.context] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun context(context: JsonField) = apply { + this.context = context + } + + fun source(source: Source) = source(JsonField.of(source)) + + /** + * Sets [Builder.source] to an arbitrary JSON value. + * + * You should usually call [Builder.source] with a well-typed [Source] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun source(source: JsonField) = apply { this.source = source } + + fun title(title: String) = title(JsonField.of(title)) + + /** + * Sets [Builder.title] to an arbitrary JSON value. + * + * You should usually call [Builder.title] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun title(title: JsonField) = apply { this.title = title } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("document") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionDocumentObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .citations() + * .context() + * .source() + * .title() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionDocumentObject = + ChatCompletionDocumentObject( + checkRequired("citations", citations), + checkRequired("context", context), + checkRequired("source", source), + checkRequired("title", title), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionDocumentObject = apply { + if (validated) { + return@apply + } + + citations().ifPresent { it.validate() } + context() + source().validate() + title() + _type().let { + if (it != JsonValue.from("document")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (citations.asKnown().getOrNull()?.validity() ?: 0) + + (if (context.asKnown().isPresent) 1 else 0) + + (source.asKnown().getOrNull()?.validity() ?: 0) + + (if (title.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("document")) 1 else 0 } + + class Citations + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val enabled: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("enabled") + @ExcludeMissing + enabled: JsonField = JsonMissing.of() + ) : this(enabled, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server + * responded with an unexpected value). + */ + fun enabled(): Boolean = enabled.getRequired("enabled") + + /** + * Returns the raw JSON value of [enabled]. + * + * Unlike [enabled], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("enabled") + @ExcludeMissing + fun _enabled(): JsonField = enabled + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [Citations]. + * + * The following fields are required: + * ```java + * .enabled() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Citations]. */ + class Builder internal constructor() { + + private var enabled: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(citations: Citations) = apply { + enabled = citations.enabled + additionalProperties = + citations.additionalProperties.toMutableMap() + } + + fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) + + /** + * Sets [Builder.enabled] to an arbitrary JSON value. + * + * You should usually call [Builder.enabled] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun enabled(enabled: JsonField) = apply { + this.enabled = enabled + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Citations]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .enabled() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Citations = + Citations( + checkRequired("enabled", enabled), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Citations = apply { + if (validated) { + return@apply + } + + enabled() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (enabled.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Citations && + enabled == other.enabled && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(enabled, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Citations{enabled=$enabled, additionalProperties=$additionalProperties}" + } + + class Source + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val data: JsonField, + private val mediaType: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("data") + @ExcludeMissing + data: JsonField = JsonMissing.of(), + @JsonProperty("media_type") + @ExcludeMissing + mediaType: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of(), + ) : this(data, mediaType, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server + * responded with an unexpected value). + */ + fun data(): String = data.getRequired("data") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server + * responded with an unexpected value). + */ + fun mediaType(): String = mediaType.getRequired("media_type") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("text") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if + * the server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("data") + @ExcludeMissing + fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [mediaType]. + * + * Unlike [mediaType], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("media_type") + @ExcludeMissing + fun _mediaType(): JsonField = mediaType + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [Source]. + * + * The following fields are required: + * ```java + * .data() + * .mediaType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Source]. */ + class Builder internal constructor() { + + private var data: JsonField? = null + private var mediaType: JsonField? = null + private var type: JsonValue = JsonValue.from("text") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(source: Source) = apply { + data = source.data + mediaType = source.mediaType + type = source.type + additionalProperties = + source.additionalProperties.toMutableMap() + } + + fun data(data: String) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] + * value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + fun mediaType(mediaType: String) = + mediaType(JsonField.of(mediaType)) + + /** + * Sets [Builder.mediaType] to an arbitrary JSON value. + * + * You should usually call [Builder.mediaType] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun mediaType(mediaType: JsonField) = apply { + this.mediaType = mediaType + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("text") + * ``` + * + * This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Source]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .data() + * .mediaType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Source = + Source( + checkRequired("data", data), + checkRequired("mediaType", mediaType), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Source = apply { + if (validated) { + return@apply + } + + data() + mediaType() + _type().let { + if (it != JsonValue.from("text")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (if (mediaType.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("text")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Source && + data == other.data && + mediaType == other.mediaType && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(data, mediaType, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Source{data=$data, mediaType=$mediaType, type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionDocumentObject && + citations == other.citations && + context == other.context && + source == other.source && + title == other.title && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + citations, + context, + source, + title, + type, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionDocumentObject{citations=$citations, context=$context, source=$source, title=$title, type=$type, additionalProperties=$additionalProperties}" + } + + class ChatCompletionVideoObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val videoUrl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of(), + @JsonProperty("video_url") + @ExcludeMissing + videoUrl: JsonField = JsonMissing.of(), + ) : this(type, videoUrl, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("video_url") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun videoUrl(): VideoUrl = videoUrl.getRequired("video_url") + + /** + * Returns the raw JSON value of [videoUrl]. + * + * Unlike [videoUrl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("video_url") + @ExcludeMissing + fun _videoUrl(): JsonField = videoUrl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionVideoObject]. + * + * The following fields are required: + * ```java + * .videoUrl() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionVideoObject]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("video_url") + private var videoUrl: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionVideoObject: ChatCompletionVideoObject + ) = apply { + type = chatCompletionVideoObject.type + videoUrl = chatCompletionVideoObject.videoUrl + additionalProperties = + chatCompletionVideoObject.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("video_url") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun videoUrl(videoUrl: VideoUrl) = videoUrl(JsonField.of(videoUrl)) + + /** + * Sets [Builder.videoUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.videoUrl] with a well-typed + * [VideoUrl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun videoUrl(videoUrl: JsonField) = apply { + this.videoUrl = videoUrl + } + + /** Alias for calling [videoUrl] with `VideoUrl.ofString(string)`. */ + fun videoUrl(string: String) = videoUrl(VideoUrl.ofString(string)) + + /** + * Alias for calling [videoUrl] with + * `VideoUrl.ofChatCompletionVideoUrlObject(chatCompletionVideoUrlObject)`. + */ + fun videoUrl( + chatCompletionVideoUrlObject: VideoUrl.ChatCompletionVideoUrlObject + ) = + videoUrl( + VideoUrl.ofChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject + ) + ) + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionVideoObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .videoUrl() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionVideoObject = + ChatCompletionVideoObject( + type, + checkRequired("videoUrl", videoUrl), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionVideoObject = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("video_url")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + videoUrl().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("video_url")) 1 else 0 } + + (videoUrl.asKnown().getOrNull()?.validity() ?: 0) + + @JsonDeserialize(using = VideoUrl.Deserializer::class) + @JsonSerialize(using = VideoUrl.Serializer::class) + class VideoUrl + private constructor( + private val string: String? = null, + private val chatCompletionVideoUrlObject: + ChatCompletionVideoUrlObject? = + null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun chatCompletionVideoUrlObject(): + Optional = + Optional.ofNullable(chatCompletionVideoUrlObject) + + fun isString(): Boolean = string != null + + fun isChatCompletionVideoUrlObject(): Boolean = + chatCompletionVideoUrlObject != null + + fun asString(): String = string.getOrThrow("string") + + fun asChatCompletionVideoUrlObject(): ChatCompletionVideoUrlObject = + chatCompletionVideoUrlObject.getOrThrow( + "chatCompletionVideoUrlObject" + ) + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + chatCompletionVideoUrlObject != null -> + visitor.visitChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): VideoUrl = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject: + ChatCompletionVideoUrlObject + ) { + chatCompletionVideoUrlObject.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject: + ChatCompletionVideoUrlObject + ) = chatCompletionVideoUrlObject.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VideoUrl && + string == other.string && + chatCompletionVideoUrlObject == + other.chatCompletionVideoUrlObject + } + + override fun hashCode(): Int = + Objects.hash(string, chatCompletionVideoUrlObject) + + override fun toString(): String = + when { + string != null -> "VideoUrl{string=$string}" + chatCompletionVideoUrlObject != null -> + "VideoUrl{chatCompletionVideoUrlObject=$chatCompletionVideoUrlObject}" + _json != null -> "VideoUrl{_unknown=$_json}" + else -> throw IllegalStateException("Invalid VideoUrl") + } + + companion object { + + @JvmStatic fun ofString(string: String) = VideoUrl(string = string) + + @JvmStatic + fun ofChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject: ChatCompletionVideoUrlObject + ) = + VideoUrl( + chatCompletionVideoUrlObject = chatCompletionVideoUrlObject + ) + } + + /** + * An interface that defines how to map each variant of [VideoUrl] to a + * value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject: ChatCompletionVideoUrlObject + ): T + + /** + * Maps an unknown variant of [VideoUrl] to a value of type [T]. + * + * An instance of [VideoUrl] can contain an unknown variant if it + * was deserialized from data that doesn't match any known variant. + * For example, if the SDK is on an older version than the API, then + * the API may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown VideoUrl: $json") + } + } + + internal class Deserializer : + BaseDeserializer(VideoUrl::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): VideoUrl { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef< + ChatCompletionVideoUrlObject + >(), + ) + ?.let { + VideoUrl( + chatCompletionVideoUrlObject = it, + _json = json, + ) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { VideoUrl(string = it, _json = json) }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. + // deserializing from boolean). + 0 -> VideoUrl(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, + // then use the first completely valid match, or simply the + // first match if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } + ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(VideoUrl::class) { + + override fun serialize( + value: VideoUrl, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.chatCompletionVideoUrlObject != null -> + generator.writeObject( + value.chatCompletionVideoUrlObject + ) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid VideoUrl") + } + } + } + + class ChatCompletionVideoUrlObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val url: JsonField, + private val detail: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") + @ExcludeMissing + url: JsonField = JsonMissing.of(), + @JsonProperty("detail") + @ExcludeMissing + detail: JsonField = JsonMissing.of(), + ) : this(url, detail, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an + * unexpected type or is unexpectedly missing or null (e.g. if the + * server responded with an unexpected value). + */ + fun url(): String = url.getRequired("url") + + /** + * @throws HanzoInvalidDataException if the JSON field has an + * unexpected type (e.g. if the server responded with an + * unexpected value). + */ + fun detail(): Optional = detail.getOptional("detail") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("url") + @ExcludeMissing + fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [detail]. + * + * Unlike [detail], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("detail") + @ExcludeMissing + fun _detail(): JsonField = detail + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionVideoUrlObject]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionVideoUrlObject]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var detail: JsonField = JsonMissing.of() + private var additionalProperties: + MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionVideoUrlObject: ChatCompletionVideoUrlObject + ) = apply { + url = chatCompletionVideoUrlObject.url + detail = chatCompletionVideoUrlObject.detail + additionalProperties = + chatCompletionVideoUrlObject.additionalProperties + .toMutableMap() + } + + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed + * [String] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun detail(detail: String) = detail(JsonField.of(detail)) + + /** + * Sets [Builder.detail] to an arbitrary JSON value. + * + * You should usually call [Builder.detail] with a well-typed + * [String] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun detail(detail: JsonField) = apply { + this.detail = detail + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = + apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of + * [ChatCompletionVideoUrlObject]. + * + * Further updates to this [Builder] will not mutate the + * returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionVideoUrlObject = + ChatCompletionVideoUrlObject( + checkRequired("url", url), + detail, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionVideoUrlObject = apply { + if (validated) { + return@apply + } + + url() + detail() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (url.asKnown().isPresent) 1 else 0) + + (if (detail.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionVideoUrlObject && + url == other.url && + detail == other.detail && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(url, detail, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionVideoUrlObject{url=$url, detail=$detail, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionVideoObject && + type == other.type && + videoUrl == other.videoUrl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, videoUrl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionVideoObject{type=$type, videoUrl=$videoUrl, additionalProperties=$additionalProperties}" + } + + class ChatCompletionFileObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val file: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("file") + @ExcludeMissing + file: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + ) : this(file, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun file(): File = file.getRequired("file") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("file") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [file]. + * + * Unlike [file], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("file") @ExcludeMissing fun _file(): JsonField = file + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionFileObject]. + * + * The following fields are required: + * ```java + * .file() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionFileObject]. */ + class Builder internal constructor() { + + private var file: JsonField? = null + private var type: JsonValue = JsonValue.from("file") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionFileObject: ChatCompletionFileObject) = + apply { + file = chatCompletionFileObject.file + type = chatCompletionFileObject.type + additionalProperties = + chatCompletionFileObject.additionalProperties.toMutableMap() + } + + fun file(file: File) = file(JsonField.of(file)) + + /** + * Sets [Builder.file] to an arbitrary JSON value. + * + * You should usually call [Builder.file] with a well-typed [File] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun file(file: JsonField) = apply { this.file = file } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("file") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionFileObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .file() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionFileObject = + ChatCompletionFileObject( + checkRequired("file", file), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionFileObject = apply { + if (validated) { + return@apply + } + + file().validate() + _type().let { + if (it != JsonValue.from("file")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (file.asKnown().getOrNull()?.validity() ?: 0) + + type.let { if (it == JsonValue.from("file")) 1 else 0 } + + class File + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val fileData: JsonField, + private val fileId: JsonField, + private val filename: JsonField, + private val format: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("file_data") + @ExcludeMissing + fileData: JsonField = JsonMissing.of(), + @JsonProperty("file_id") + @ExcludeMissing + fileId: JsonField = JsonMissing.of(), + @JsonProperty("filename") + @ExcludeMissing + filename: JsonField = JsonMissing.of(), + @JsonProperty("format") + @ExcludeMissing + format: JsonField = JsonMissing.of(), + ) : this(fileData, fileId, filename, format, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun fileData(): Optional = fileData.getOptional("file_data") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun fileId(): Optional = fileId.getOptional("file_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun filename(): Optional = filename.getOptional("filename") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun format(): Optional = format.getOptional("format") + + /** + * Returns the raw JSON value of [fileData]. + * + * Unlike [fileData], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("file_data") + @ExcludeMissing + fun _fileData(): JsonField = fileData + + /** + * Returns the raw JSON value of [fileId]. + * + * Unlike [fileId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("file_id") + @ExcludeMissing + fun _fileId(): JsonField = fileId + + /** + * Returns the raw JSON value of [filename]. + * + * Unlike [filename], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("filename") + @ExcludeMissing + fun _filename(): JsonField = filename + + /** + * Returns the raw JSON value of [format]. + * + * Unlike [format], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("format") + @ExcludeMissing + fun _format(): JsonField = format + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [File]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [File]. */ + class Builder internal constructor() { + + private var fileData: JsonField = JsonMissing.of() + private var fileId: JsonField = JsonMissing.of() + private var filename: JsonField = JsonMissing.of() + private var format: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(file: File) = apply { + fileData = file.fileData + fileId = file.fileId + filename = file.filename + format = file.format + additionalProperties = file.additionalProperties.toMutableMap() + } + + fun fileData(fileData: String) = fileData(JsonField.of(fileData)) + + /** + * Sets [Builder.fileData] to an arbitrary JSON value. + * + * You should usually call [Builder.fileData] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun fileData(fileData: JsonField) = apply { + this.fileData = fileData + } + + fun fileId(fileId: String) = fileId(JsonField.of(fileId)) + + /** + * Sets [Builder.fileId] to an arbitrary JSON value. + * + * You should usually call [Builder.fileId] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun fileId(fileId: JsonField) = apply { + this.fileId = fileId + } + + fun filename(filename: String) = filename(JsonField.of(filename)) + + /** + * Sets [Builder.filename] to an arbitrary JSON value. + * + * You should usually call [Builder.filename] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun filename(filename: JsonField) = apply { + this.filename = filename + } + + fun format(format: String) = format(JsonField.of(format)) + + /** + * Sets [Builder.format] to an arbitrary JSON value. + * + * You should usually call [Builder.format] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun format(format: JsonField) = apply { + this.format = format + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [File]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): File = + File( + fileData, + fileId, + filename, + format, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): File = apply { + if (validated) { + return@apply + } + + fileData() + fileId() + filename() + format() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (fileData.asKnown().isPresent) 1 else 0) + + (if (fileId.asKnown().isPresent) 1 else 0) + + (if (filename.asKnown().isPresent) 1 else 0) + + (if (format.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is File && + fileData == other.fileData && + fileId == other.fileId && + filename == other.filename && + format == other.format && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + fileData, + fileId, + filename, + format, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "File{fileData=$fileData, fileId=$fileId, filename=$filename, format=$format, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionFileObject && + file == other.file && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(file, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionFileObject{file=$file, type=$type, additionalProperties=$additionalProperties}" + } + } + } + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CacheControl]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionUserMessage && + content == other.content && + role == other.role && + cacheControl == other.cacheControl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(content, role, cacheControl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionUserMessage{content=$content, role=$role, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" + } + + class ChatCompletionAssistantMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val role: JsonValue, + private val cacheControl: JsonField, + private val content: JsonField, + private val functionCall: JsonField, + private val name: JsonField, + private val reasoningContent: JsonField, + private val thinkingBlocks: JsonField>, + private val toolCalls: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("function_call") + @ExcludeMissing + functionCall: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("reasoning_content") + @ExcludeMissing + reasoningContent: JsonField = JsonMissing.of(), + @JsonProperty("thinking_blocks") + @ExcludeMissing + thinkingBlocks: JsonField> = JsonMissing.of(), + @JsonProperty("tool_calls") + @ExcludeMissing + toolCalls: JsonField> = JsonMissing.of(), + ) : this( + role, + cacheControl, + content, + functionCall, + name, + reasoningContent, + thinkingBlocks, + toolCalls, + mutableMapOf(), + ) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("assistant") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun cacheControl(): Optional = cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun functionCall(): Optional = functionCall.getOptional("function_call") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun reasoningContent(): Optional = + reasoningContent.getOptional("reasoning_content") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun thinkingBlocks(): Optional> = + thinkingBlocks.getOptional("thinking_blocks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun toolCalls(): Optional> = toolCalls.getOptional("tool_calls") + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [functionCall]. + * + * Unlike [functionCall], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_call") + @ExcludeMissing + fun _functionCall(): JsonField = functionCall + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [reasoningContent]. + * + * Unlike [reasoningContent], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("reasoning_content") + @ExcludeMissing + fun _reasoningContent(): JsonField = reasoningContent + + /** + * Returns the raw JSON value of [thinkingBlocks]. + * + * Unlike [thinkingBlocks], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("thinking_blocks") + @ExcludeMissing + fun _thinkingBlocks(): JsonField> = thinkingBlocks + + /** + * Returns the raw JSON value of [toolCalls]. + * + * Unlike [toolCalls], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tool_calls") + @ExcludeMissing + fun _toolCalls(): JsonField> = toolCalls + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionAssistantMessage]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionAssistantMessage]. */ + class Builder internal constructor() { + + private var role: JsonValue = JsonValue.from("assistant") + private var cacheControl: JsonField = JsonMissing.of() + private var content: JsonField = JsonMissing.of() + private var functionCall: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var reasoningContent: JsonField = JsonMissing.of() + private var thinkingBlocks: JsonField>? = null + private var toolCalls: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionAssistantMessage: ChatCompletionAssistantMessage) = + apply { + role = chatCompletionAssistantMessage.role + cacheControl = chatCompletionAssistantMessage.cacheControl + content = chatCompletionAssistantMessage.content + functionCall = chatCompletionAssistantMessage.functionCall + name = chatCompletionAssistantMessage.name + reasoningContent = chatCompletionAssistantMessage.reasoningContent + thinkingBlocks = + chatCompletionAssistantMessage.thinkingBlocks.map { it.toMutableList() } + toolCalls = + chatCompletionAssistantMessage.toolCalls.map { it.toMutableList() } + additionalProperties = + chatCompletionAssistantMessage.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("assistant") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed [CacheControl] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun content(content: Content?) = content(JsonField.ofNullable(content)) + + /** Alias for calling [Builder.content] with `content.orElse(null)`. */ + fun content(content: Optional) = content(content.getOrNull()) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** + * Alias for calling [content] with + * `Content.ofUnnamedSchemaWithArrayParent5s(unnamedSchemaWithArrayParent5s)`. + */ + fun contentOfUnnamedSchemaWithArrayParent5s( + unnamedSchemaWithArrayParent5s: List + ) = + content( + Content.ofUnnamedSchemaWithArrayParent5s(unnamedSchemaWithArrayParent5s) + ) + + fun functionCall(functionCall: FunctionCall?) = + functionCall(JsonField.ofNullable(functionCall)) + + /** Alias for calling [Builder.functionCall] with `functionCall.orElse(null)`. */ + fun functionCall(functionCall: Optional) = + functionCall(functionCall.getOrNull()) + + /** + * Sets [Builder.functionCall] to an arbitrary JSON value. + * + * You should usually call [Builder.functionCall] with a well-typed [FunctionCall] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun functionCall(functionCall: JsonField) = apply { + this.functionCall = functionCall + } + + fun name(name: String?) = name(JsonField.ofNullable(name)) + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun reasoningContent(reasoningContent: String?) = + reasoningContent(JsonField.ofNullable(reasoningContent)) + + /** + * Alias for calling [Builder.reasoningContent] with + * `reasoningContent.orElse(null)`. + */ + fun reasoningContent(reasoningContent: Optional) = + reasoningContent(reasoningContent.getOrNull()) + + /** + * Sets [Builder.reasoningContent] to an arbitrary JSON value. + * + * You should usually call [Builder.reasoningContent] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun reasoningContent(reasoningContent: JsonField) = apply { + this.reasoningContent = reasoningContent + } + + fun thinkingBlocks(thinkingBlocks: List?) = + thinkingBlocks(JsonField.ofNullable(thinkingBlocks)) + + /** + * Alias for calling [Builder.thinkingBlocks] with `thinkingBlocks.orElse(null)`. + */ + fun thinkingBlocks(thinkingBlocks: Optional>) = + thinkingBlocks(thinkingBlocks.getOrNull()) + + /** + * Sets [Builder.thinkingBlocks] to an arbitrary JSON value. + * + * You should usually call [Builder.thinkingBlocks] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun thinkingBlocks(thinkingBlocks: JsonField>) = apply { + this.thinkingBlocks = thinkingBlocks.map { it.toMutableList() } + } + + /** + * Adds a single [ThinkingBlock] to [thinkingBlocks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addThinkingBlock(thinkingBlock: ThinkingBlock) = apply { + thinkingBlocks = + (thinkingBlocks ?: JsonField.of(mutableListOf())).also { + checkKnown("thinkingBlocks", it).add(thinkingBlock) + } + } + + /** + * Alias for calling [addThinkingBlock] with + * `ThinkingBlock.ofChatCompletion(chatCompletion)`. + */ + fun addThinkingBlock(chatCompletion: ThinkingBlock.ChatCompletionThinkingBlock) = + addThinkingBlock(ThinkingBlock.ofChatCompletion(chatCompletion)) + + /** + * Alias for calling [addThinkingBlock] with + * `ThinkingBlock.ofChatCompletionRedacted(chatCompletionRedacted)`. + */ + fun addThinkingBlock( + chatCompletionRedacted: ThinkingBlock.ChatCompletionRedactedThinkingBlock + ) = addThinkingBlock(ThinkingBlock.ofChatCompletionRedacted(chatCompletionRedacted)) + + fun toolCalls(toolCalls: List?) = + toolCalls(JsonField.ofNullable(toolCalls)) + + /** Alias for calling [Builder.toolCalls] with `toolCalls.orElse(null)`. */ + fun toolCalls(toolCalls: Optional>) = + toolCalls(toolCalls.getOrNull()) + + /** + * Sets [Builder.toolCalls] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCalls] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun toolCalls(toolCalls: JsonField>) = apply { + this.toolCalls = toolCalls.map { it.toMutableList() } + } + + /** + * Adds a single [ToolCall] to [toolCalls]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addToolCall(toolCall: ToolCall) = apply { + toolCalls = + (toolCalls ?: JsonField.of(mutableListOf())).also { + checkKnown("toolCalls", it).add(toolCall) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionAssistantMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ChatCompletionAssistantMessage = + ChatCompletionAssistantMessage( + role, + cacheControl, + content, + functionCall, + name, + reasoningContent, + (thinkingBlocks ?: JsonMissing.of()).map { it.toImmutable() }, + (toolCalls ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionAssistantMessage = apply { + if (validated) { + return@apply + } + + _role().let { + if (it != JsonValue.from("assistant")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + content().ifPresent { it.validate() } + functionCall().ifPresent { it.validate() } + name() + reasoningContent() + thinkingBlocks().ifPresent { it.forEach { it.validate() } } + toolCalls().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + role.let { if (it == JsonValue.from("assistant")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (content.asKnown().getOrNull()?.validity() ?: 0) + + (functionCall.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (reasoningContent.asKnown().isPresent) 1 else 0) + + (thinkingBlocks.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (toolCalls.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CacheControl]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val unnamedSchemaWithArrayParent5s: List? = + null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun unnamedSchemaWithArrayParent5s(): + Optional> = + Optional.ofNullable(unnamedSchemaWithArrayParent5s) + + fun isString(): Boolean = string != null + + fun isUnnamedSchemaWithArrayParent5s(): Boolean = + unnamedSchemaWithArrayParent5s != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnnamedSchemaWithArrayParent5s(): List = + unnamedSchemaWithArrayParent5s.getOrThrow("unnamedSchemaWithArrayParent5s") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + unnamedSchemaWithArrayParent5s != null -> + visitor.visitUnnamedSchemaWithArrayParent5s( + unnamedSchemaWithArrayParent5s + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitUnnamedSchemaWithArrayParent5s( + unnamedSchemaWithArrayParent5s: List + ) { + unnamedSchemaWithArrayParent5s.forEach { it.validate() } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitUnnamedSchemaWithArrayParent5s( + unnamedSchemaWithArrayParent5s: List + ) = unnamedSchemaWithArrayParent5s.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + unnamedSchemaWithArrayParent5s == other.unnamedSchemaWithArrayParent5s + } + + override fun hashCode(): Int = Objects.hash(string, unnamedSchemaWithArrayParent5s) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + unnamedSchemaWithArrayParent5s != null -> + "Content{unnamedSchemaWithArrayParent5s=$unnamedSchemaWithArrayParent5s}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofUnnamedSchemaWithArrayParent5s( + unnamedSchemaWithArrayParent5s: List + ) = + Content( + unnamedSchemaWithArrayParent5s = + unnamedSchemaWithArrayParent5s.toImmutable() + ) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitUnnamedSchemaWithArrayParent5s( + unnamedSchemaWithArrayParent5s: List + ): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { + Content( + unnamedSchemaWithArrayParent5s = it, + _json = json, + ) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unnamedSchemaWithArrayParent5s != null -> + generator.writeObject(value.unnamedSchemaWithArrayParent5s) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + + @JsonDeserialize(using = UnnamedSchemaWithArrayParent5.Deserializer::class) + @JsonSerialize(using = UnnamedSchemaWithArrayParent5.Serializer::class) + class UnnamedSchemaWithArrayParent5 + private constructor( + private val chatCompletionTextObject: ChatCompletionTextObject? = null, + private val chatCompletionThinkingBlock: ChatCompletionThinkingBlock? = null, + private val _json: JsonValue? = null, + ) { + + fun chatCompletionTextObject(): Optional = + Optional.ofNullable(chatCompletionTextObject) + + fun chatCompletionThinkingBlock(): Optional = + Optional.ofNullable(chatCompletionThinkingBlock) + + fun isChatCompletionTextObject(): Boolean = chatCompletionTextObject != null + + fun isChatCompletionThinkingBlock(): Boolean = + chatCompletionThinkingBlock != null + + fun asChatCompletionTextObject(): ChatCompletionTextObject = + chatCompletionTextObject.getOrThrow("chatCompletionTextObject") + + fun asChatCompletionThinkingBlock(): ChatCompletionThinkingBlock = + chatCompletionThinkingBlock.getOrThrow("chatCompletionThinkingBlock") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + chatCompletionTextObject != null -> + visitor.visitChatCompletionTextObject(chatCompletionTextObject) + chatCompletionThinkingBlock != null -> + visitor.visitChatCompletionThinkingBlock( + chatCompletionThinkingBlock + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnnamedSchemaWithArrayParent5 = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) { + chatCompletionTextObject.validate() + } + + override fun visitChatCompletionThinkingBlock( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ) { + chatCompletionThinkingBlock.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) = chatCompletionTextObject.validity() + + override fun visitChatCompletionThinkingBlock( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ) = chatCompletionThinkingBlock.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnnamedSchemaWithArrayParent5 && + chatCompletionTextObject == other.chatCompletionTextObject && + chatCompletionThinkingBlock == other.chatCompletionThinkingBlock + } + + override fun hashCode(): Int = + Objects.hash(chatCompletionTextObject, chatCompletionThinkingBlock) + + override fun toString(): String = + when { + chatCompletionTextObject != null -> + "UnnamedSchemaWithArrayParent5{chatCompletionTextObject=$chatCompletionTextObject}" + chatCompletionThinkingBlock != null -> + "UnnamedSchemaWithArrayParent5{chatCompletionThinkingBlock=$chatCompletionThinkingBlock}" + _json != null -> "UnnamedSchemaWithArrayParent5{_unknown=$_json}" + else -> + throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent5") + } + + companion object { + + @JvmStatic + fun ofChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) = + UnnamedSchemaWithArrayParent5( + chatCompletionTextObject = chatCompletionTextObject + ) + + @JvmStatic + fun ofChatCompletionThinkingBlock( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ) = + UnnamedSchemaWithArrayParent5( + chatCompletionThinkingBlock = chatCompletionThinkingBlock + ) + } + + /** + * An interface that defines how to map each variant of + * [UnnamedSchemaWithArrayParent5] to a value of type [T]. + */ + interface Visitor { + + fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ): T + + fun visitChatCompletionThinkingBlock( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ): T + + /** + * Maps an unknown variant of [UnnamedSchemaWithArrayParent5] to a value of + * type [T]. + * + * An instance of [UnnamedSchemaWithArrayParent5] can contain an unknown + * variant if it was deserialized from data that doesn't match any known + * variant. For example, if the SDK is on an older version than the API, + * then the API may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException( + "Unknown UnnamedSchemaWithArrayParent5: $json" + ) + } + } + + internal class Deserializer : + BaseDeserializer( + UnnamedSchemaWithArrayParent5::class + ) { + + override fun ObjectCodec.deserialize( + node: JsonNode + ): UnnamedSchemaWithArrayParent5 { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent5( + chatCompletionTextObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent5( + chatCompletionThinkingBlock = it, + _json = json, + ) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing + // from boolean). + 0 -> UnnamedSchemaWithArrayParent5(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then + // use the first completely valid match, or simply the first match + // if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer( + UnnamedSchemaWithArrayParent5::class + ) { + + override fun serialize( + value: UnnamedSchemaWithArrayParent5, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.chatCompletionTextObject != null -> + generator.writeObject(value.chatCompletionTextObject) + value.chatCompletionThinkingBlock != null -> + generator.writeObject(value.chatCompletionThinkingBlock) + value._json != null -> generator.writeObject(value._json) + else -> + throw IllegalStateException( + "Invalid UnnamedSchemaWithArrayParent5" + ) + } + } + } + + class ChatCompletionTextObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val text: JsonField, + private val type: JsonValue, + private val cacheControl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("text") + @ExcludeMissing + text: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + ) : this(text, type, cacheControl, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun text(): String = text.getRequired("text") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("text") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * Returns the raw JSON value of [text]. + * + * Unlike [text], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("text") @ExcludeMissing fun _text(): JsonField = text + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionTextObject]. + * + * The following fields are required: + * ```java + * .text() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionTextObject]. */ + class Builder internal constructor() { + + private var text: JsonField? = null + private var type: JsonValue = JsonValue.from("text") + private var cacheControl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionTextObject: ChatCompletionTextObject) = + apply { + text = chatCompletionTextObject.text + type = chatCompletionTextObject.type + cacheControl = chatCompletionTextObject.cacheControl + additionalProperties = + chatCompletionTextObject.additionalProperties.toMutableMap() + } + + fun text(text: String) = text(JsonField.of(text)) + + /** + * Sets [Builder.text] to an arbitrary JSON value. + * + * You should usually call [Builder.text] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun text(text: JsonField) = apply { this.text = text } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("text") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionTextObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .text() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionTextObject = + ChatCompletionTextObject( + checkRequired("text", text), + type, + cacheControl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionTextObject = apply { + if (validated) { + return@apply + } + + text() + _type().let { + if (it != JsonValue.from("text")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + cacheControl().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (text.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("text")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if + * the server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [CacheControl]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = + cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionTextObject && + text == other.text && + type == other.type && + cacheControl == other.cacheControl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(text, type, cacheControl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionTextObject{text=$text, type=$type, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" + } + + class ChatCompletionThinkingBlock + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val cacheControl: JsonField, + private val signature: JsonField, + private val thinking: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("signature") + @ExcludeMissing + signature: JsonField = JsonMissing.of(), + @JsonProperty("thinking") + @ExcludeMissing + thinking: JsonField = JsonMissing.of(), + ) : this(type, cacheControl, signature, thinking, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("thinking") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun signature(): Optional = signature.getOptional("signature") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun thinking(): Optional = thinking.getOptional("thinking") + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [signature]. + * + * Unlike [signature], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("signature") + @ExcludeMissing + fun _signature(): JsonField = signature + + /** + * Returns the raw JSON value of [thinking]. + * + * Unlike [thinking], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("thinking") + @ExcludeMissing + fun _thinking(): JsonField = thinking + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionThinkingBlock]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionThinkingBlock]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("thinking") + private var cacheControl: JsonField = JsonMissing.of() + private var signature: JsonField = JsonMissing.of() + private var thinking: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ) = apply { + type = chatCompletionThinkingBlock.type + cacheControl = chatCompletionThinkingBlock.cacheControl + signature = chatCompletionThinkingBlock.signature + thinking = chatCompletionThinkingBlock.thinking + additionalProperties = + chatCompletionThinkingBlock.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("thinking") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl?) = + cacheControl(JsonField.ofNullable(cacheControl)) + + /** + * Alias for calling [Builder.cacheControl] with + * `cacheControl.orElse(null)`. + */ + fun cacheControl(cacheControl: Optional) = + cacheControl(cacheControl.getOrNull()) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofUnionMember0(unionMember0)`. + */ + fun cacheControl(unionMember0: CacheControl.UnionMember0) = + cacheControl(CacheControl.ofUnionMember0(unionMember0)) + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofChatCompletionCachedContent()`. + */ + fun cacheControlChatCompletionCachedContent() = + cacheControl(CacheControl.ofChatCompletionCachedContent()) + + fun signature(signature: String) = signature(JsonField.of(signature)) + + /** + * Sets [Builder.signature] to an arbitrary JSON value. + * + * You should usually call [Builder.signature] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun signature(signature: JsonField) = apply { + this.signature = signature + } + + fun thinking(thinking: String) = thinking(JsonField.of(thinking)) + + /** + * Sets [Builder.thinking] to an arbitrary JSON value. + * + * You should usually call [Builder.thinking] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun thinking(thinking: JsonField) = apply { + this.thinking = thinking + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionThinkingBlock]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): ChatCompletionThinkingBlock = + ChatCompletionThinkingBlock( + type, + cacheControl, + signature, + thinking, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionThinkingBlock = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("thinking")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + cacheControl().ifPresent { it.validate() } + signature() + thinking() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("thinking")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (if (signature.asKnown().isPresent) 1 else 0) + + (if (thinking.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = CacheControl.Deserializer::class) + @JsonSerialize(using = CacheControl.Serializer::class) + class CacheControl + private constructor( + private val unionMember0: UnionMember0? = null, + private val chatCompletionCachedContent: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun unionMember0(): Optional = + Optional.ofNullable(unionMember0) + + fun chatCompletionCachedContent(): Optional = + Optional.ofNullable(chatCompletionCachedContent) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isChatCompletionCachedContent(): Boolean = + chatCompletionCachedContent != null + + fun asUnionMember0(): UnionMember0 = + unionMember0.getOrThrow("unionMember0") + + fun asChatCompletionCachedContent(): JsonValue = + chatCompletionCachedContent.getOrThrow( + "chatCompletionCachedContent" + ) + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + unionMember0 != null -> visitor.visitUnionMember0(unionMember0) + chatCompletionCachedContent != null -> + visitor.visitChatCompletionCachedContent( + chatCompletionCachedContent + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) { + unionMember0.validate() + } + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) { + chatCompletionCachedContent.let { + if ( + it != + JsonValue.from(mapOf("type" to "ephemeral")) + ) { + throw HanzoInvalidDataException( + "'chatCompletionCachedContent' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) = + unionMember0.validity() + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) = + chatCompletionCachedContent.let { + if ( + it == + JsonValue.from(mapOf("type" to "ephemeral")) + ) + 1 + else 0 + } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + unionMember0 == other.unionMember0 && + chatCompletionCachedContent == other.chatCompletionCachedContent + } + + override fun hashCode(): Int = + Objects.hash(unionMember0, chatCompletionCachedContent) + + override fun toString(): String = + when { + unionMember0 != null -> + "CacheControl{unionMember0=$unionMember0}" + chatCompletionCachedContent != null -> + "CacheControl{chatCompletionCachedContent=$chatCompletionCachedContent}" + _json != null -> "CacheControl{_unknown=$_json}" + else -> throw IllegalStateException("Invalid CacheControl") + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + CacheControl(unionMember0 = unionMember0) + + @JvmStatic + fun ofChatCompletionCachedContent() = + CacheControl( + chatCompletionCachedContent = + JsonValue.from(mapOf("type" to "ephemeral")) + ) + } + + /** + * An interface that defines how to map each variant of [CacheControl] + * to a value of type [T]. + */ + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ): T + + /** + * Maps an unknown variant of [CacheControl] to a value of type [T]. + * + * An instance of [CacheControl] can contain an unknown variant if + * it was deserialized from data that doesn't match any known + * variant. For example, if the SDK is on an older version than the + * API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown CacheControl: $json") + } + } + + internal class Deserializer : + BaseDeserializer(CacheControl::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): CacheControl { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl( + chatCompletionCachedContent = it, + _json = json, + ) + } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl( + unionMember0 = it, + _json = json, + ) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. + // deserializing from boolean). + 0 -> CacheControl(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, + // then use the first completely valid match, or simply the + // first match if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } + ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer(CacheControl::class) { + + override fun serialize( + value: CacheControl, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.unionMember0 != null -> + generator.writeObject(value.unionMember0) + value.chatCompletionCachedContent != null -> + generator.writeObject(value.chatCompletionCachedContent) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid CacheControl") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UnionMember0]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember0]. */ + class Builder internal constructor() { + + private var additionalProperties: + MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember0: UnionMember0) = apply { + additionalProperties = + unionMember0.additionalProperties.toMutableMap() + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = + apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember0]. + * + * Further updates to this [Builder] will not mutate the + * returned instance. + */ + fun build(): UnionMember0 = + UnionMember0(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember0 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember0 && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UnionMember0{additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionThinkingBlock && + type == other.type && + cacheControl == other.cacheControl && + signature == other.signature && + thinking == other.thinking && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + type, + cacheControl, + signature, + thinking, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionThinkingBlock{type=$type, cacheControl=$cacheControl, signature=$signature, thinking=$thinking, additionalProperties=$additionalProperties}" + } + } + } + + class FunctionCall + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val arguments: JsonField, + private val name: JsonField, + private val providerSpecificFields: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("arguments") + @ExcludeMissing + arguments: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("provider_specific_fields") + @ExcludeMissing + providerSpecificFields: JsonField = JsonMissing.of(), + ) : this(arguments, name, providerSpecificFields, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun arguments(): Optional = arguments.getOptional("arguments") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun providerSpecificFields(): Optional = + providerSpecificFields.getOptional("provider_specific_fields") + + /** + * Returns the raw JSON value of [arguments]. + * + * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("arguments") + @ExcludeMissing + fun _arguments(): JsonField = arguments + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [providerSpecificFields]. + * + * Unlike [providerSpecificFields], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("provider_specific_fields") + @ExcludeMissing + fun _providerSpecificFields(): JsonField = + providerSpecificFields + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FunctionCall]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionCall]. */ + class Builder internal constructor() { + + private var arguments: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var providerSpecificFields: JsonField = + JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(functionCall: FunctionCall) = apply { + arguments = functionCall.arguments + name = functionCall.name + providerSpecificFields = functionCall.providerSpecificFields + additionalProperties = functionCall.additionalProperties.toMutableMap() + } + + fun arguments(arguments: String) = arguments(JsonField.of(arguments)) + + /** + * Sets [Builder.arguments] to an arbitrary JSON value. + * + * You should usually call [Builder.arguments] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun arguments(arguments: JsonField) = apply { + this.arguments = arguments + } + + fun name(name: String?) = name(JsonField.ofNullable(name)) + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun providerSpecificFields(providerSpecificFields: ProviderSpecificFields?) = + providerSpecificFields(JsonField.ofNullable(providerSpecificFields)) + + /** + * Alias for calling [Builder.providerSpecificFields] with + * `providerSpecificFields.orElse(null)`. + */ + fun providerSpecificFields( + providerSpecificFields: Optional + ) = providerSpecificFields(providerSpecificFields.getOrNull()) + + /** + * Sets [Builder.providerSpecificFields] to an arbitrary JSON value. + * + * You should usually call [Builder.providerSpecificFields] with a well-typed + * [ProviderSpecificFields] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun providerSpecificFields( + providerSpecificFields: JsonField + ) = apply { this.providerSpecificFields = providerSpecificFields } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FunctionCall]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FunctionCall = + FunctionCall( + arguments, + name, + providerSpecificFields, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): FunctionCall = apply { + if (validated) { + return@apply + } + + arguments() + name() + providerSpecificFields().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (arguments.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (providerSpecificFields.asKnown().getOrNull()?.validity() ?: 0) + + class ProviderSpecificFields + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ProviderSpecificFields]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProviderSpecificFields]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(providerSpecificFields: ProviderSpecificFields) = apply { + additionalProperties = + providerSpecificFields.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProviderSpecificFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProviderSpecificFields = + ProviderSpecificFields(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ProviderSpecificFields = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProviderSpecificFields && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProviderSpecificFields{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FunctionCall && + arguments == other.arguments && + name == other.name && + providerSpecificFields == other.providerSpecificFields && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(arguments, name, providerSpecificFields, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FunctionCall{arguments=$arguments, name=$name, providerSpecificFields=$providerSpecificFields, additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = ThinkingBlock.Deserializer::class) + @JsonSerialize(using = ThinkingBlock.Serializer::class) + class ThinkingBlock + private constructor( + private val chatCompletion: ChatCompletionThinkingBlock? = null, + private val chatCompletionRedacted: ChatCompletionRedactedThinkingBlock? = null, + private val _json: JsonValue? = null, + ) { + + fun chatCompletion(): Optional = + Optional.ofNullable(chatCompletion) + + fun chatCompletionRedacted(): Optional = + Optional.ofNullable(chatCompletionRedacted) + + fun isChatCompletion(): Boolean = chatCompletion != null + + fun isChatCompletionRedacted(): Boolean = chatCompletionRedacted != null + + fun asChatCompletion(): ChatCompletionThinkingBlock = + chatCompletion.getOrThrow("chatCompletion") + + fun asChatCompletionRedacted(): ChatCompletionRedactedThinkingBlock = + chatCompletionRedacted.getOrThrow("chatCompletionRedacted") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + chatCompletion != null -> visitor.visitChatCompletion(chatCompletion) + chatCompletionRedacted != null -> + visitor.visitChatCompletionRedacted(chatCompletionRedacted) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): ThinkingBlock = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitChatCompletion( + chatCompletion: ChatCompletionThinkingBlock + ) { + chatCompletion.validate() + } + + override fun visitChatCompletionRedacted( + chatCompletionRedacted: ChatCompletionRedactedThinkingBlock + ) { + chatCompletionRedacted.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitChatCompletion( + chatCompletion: ChatCompletionThinkingBlock + ) = chatCompletion.validity() + + override fun visitChatCompletionRedacted( + chatCompletionRedacted: ChatCompletionRedactedThinkingBlock + ) = chatCompletionRedacted.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ThinkingBlock && + chatCompletion == other.chatCompletion && + chatCompletionRedacted == other.chatCompletionRedacted + } + + override fun hashCode(): Int = Objects.hash(chatCompletion, chatCompletionRedacted) + + override fun toString(): String = + when { + chatCompletion != null -> "ThinkingBlock{chatCompletion=$chatCompletion}" + chatCompletionRedacted != null -> + "ThinkingBlock{chatCompletionRedacted=$chatCompletionRedacted}" + _json != null -> "ThinkingBlock{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ThinkingBlock") + } + + companion object { + + @JvmStatic + fun ofChatCompletion(chatCompletion: ChatCompletionThinkingBlock) = + ThinkingBlock(chatCompletion = chatCompletion) + + @JvmStatic + fun ofChatCompletionRedacted( + chatCompletionRedacted: ChatCompletionRedactedThinkingBlock + ) = ThinkingBlock(chatCompletionRedacted = chatCompletionRedacted) + } + + /** + * An interface that defines how to map each variant of [ThinkingBlock] to a value + * of type [T]. + */ + interface Visitor { + + fun visitChatCompletion(chatCompletion: ChatCompletionThinkingBlock): T + + fun visitChatCompletionRedacted( + chatCompletionRedacted: ChatCompletionRedactedThinkingBlock + ): T + + /** + * Maps an unknown variant of [ThinkingBlock] to a value of type [T]. + * + * An instance of [ThinkingBlock] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown ThinkingBlock: $json") + } + } + + internal class Deserializer : + BaseDeserializer(ThinkingBlock::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): ThinkingBlock { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { ThinkingBlock(chatCompletion = it, _json = json) }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + ThinkingBlock(chatCompletionRedacted = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> ThinkingBlock(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(ThinkingBlock::class) { + + override fun serialize( + value: ThinkingBlock, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.chatCompletion != null -> + generator.writeObject(value.chatCompletion) + value.chatCompletionRedacted != null -> + generator.writeObject(value.chatCompletionRedacted) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid ThinkingBlock") + } + } + } + + class ChatCompletionThinkingBlock + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val cacheControl: JsonField, + private val signature: JsonField, + private val thinking: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("signature") + @ExcludeMissing + signature: JsonField = JsonMissing.of(), + @JsonProperty("thinking") + @ExcludeMissing + thinking: JsonField = JsonMissing.of(), + ) : this(type, cacheControl, signature, thinking, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("thinking") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun signature(): Optional = signature.getOptional("signature") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun thinking(): Optional = thinking.getOptional("thinking") + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [signature]. + * + * Unlike [signature], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("signature") + @ExcludeMissing + fun _signature(): JsonField = signature + + /** + * Returns the raw JSON value of [thinking]. + * + * Unlike [thinking], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("thinking") + @ExcludeMissing + fun _thinking(): JsonField = thinking + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionThinkingBlock]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionThinkingBlock]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("thinking") + private var cacheControl: JsonField = JsonMissing.of() + private var signature: JsonField = JsonMissing.of() + private var thinking: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ) = apply { + type = chatCompletionThinkingBlock.type + cacheControl = chatCompletionThinkingBlock.cacheControl + signature = chatCompletionThinkingBlock.signature + thinking = chatCompletionThinkingBlock.thinking + additionalProperties = + chatCompletionThinkingBlock.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults + * to the following: + * ```java + * JsonValue.from("thinking") + * ``` + * + * This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl?) = + cacheControl(JsonField.ofNullable(cacheControl)) + + /** + * Alias for calling [Builder.cacheControl] with + * `cacheControl.orElse(null)`. + */ + fun cacheControl(cacheControl: Optional) = + cacheControl(cacheControl.getOrNull()) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofUnionMember0(unionMember0)`. + */ + fun cacheControl(unionMember0: CacheControl.UnionMember0) = + cacheControl(CacheControl.ofUnionMember0(unionMember0)) + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofChatCompletionCachedContent()`. + */ + fun cacheControlChatCompletionCachedContent() = + cacheControl(CacheControl.ofChatCompletionCachedContent()) + + fun signature(signature: String) = signature(JsonField.of(signature)) + + /** + * Sets [Builder.signature] to an arbitrary JSON value. + * + * You should usually call [Builder.signature] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun signature(signature: JsonField) = apply { + this.signature = signature + } + + fun thinking(thinking: String) = thinking(JsonField.of(thinking)) + + /** + * Sets [Builder.thinking] to an arbitrary JSON value. + * + * You should usually call [Builder.thinking] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun thinking(thinking: JsonField) = apply { + this.thinking = thinking + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionThinkingBlock]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ChatCompletionThinkingBlock = + ChatCompletionThinkingBlock( + type, + cacheControl, + signature, + thinking, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionThinkingBlock = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("thinking")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + signature() + thinking() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("thinking")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (if (signature.asKnown().isPresent) 1 else 0) + + (if (thinking.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = CacheControl.Deserializer::class) + @JsonSerialize(using = CacheControl.Serializer::class) + class CacheControl + private constructor( + private val unionMember0: UnionMember0? = null, + private val chatCompletionCachedContent: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun unionMember0(): Optional = + Optional.ofNullable(unionMember0) + + fun chatCompletionCachedContent(): Optional = + Optional.ofNullable(chatCompletionCachedContent) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isChatCompletionCachedContent(): Boolean = + chatCompletionCachedContent != null + + fun asUnionMember0(): UnionMember0 = unionMember0.getOrThrow("unionMember0") + + fun asChatCompletionCachedContent(): JsonValue = + chatCompletionCachedContent.getOrThrow("chatCompletionCachedContent") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + unionMember0 != null -> visitor.visitUnionMember0(unionMember0) + chatCompletionCachedContent != null -> + visitor.visitChatCompletionCachedContent( + chatCompletionCachedContent + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) { + unionMember0.validate() + } + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) { + chatCompletionCachedContent.let { + if ( + it != JsonValue.from(mapOf("type" to "ephemeral")) + ) { + throw HanzoInvalidDataException( + "'chatCompletionCachedContent' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) = + unionMember0.validity() + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) = + chatCompletionCachedContent.let { + if (it == JsonValue.from(mapOf("type" to "ephemeral"))) + 1 + else 0 + } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + unionMember0 == other.unionMember0 && + chatCompletionCachedContent == other.chatCompletionCachedContent + } + + override fun hashCode(): Int = + Objects.hash(unionMember0, chatCompletionCachedContent) + + override fun toString(): String = + when { + unionMember0 != null -> "CacheControl{unionMember0=$unionMember0}" + chatCompletionCachedContent != null -> + "CacheControl{chatCompletionCachedContent=$chatCompletionCachedContent}" + _json != null -> "CacheControl{_unknown=$_json}" + else -> throw IllegalStateException("Invalid CacheControl") + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + CacheControl(unionMember0 = unionMember0) + + @JvmStatic + fun ofChatCompletionCachedContent() = + CacheControl( + chatCompletionCachedContent = + JsonValue.from(mapOf("type" to "ephemeral")) + ) + } + + /** + * An interface that defines how to map each variant of [CacheControl] to a + * value of type [T]. + */ + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ): T + + /** + * Maps an unknown variant of [CacheControl] to a value of type [T]. + * + * An instance of [CacheControl] can contain an unknown variant if it + * was deserialized from data that doesn't match any known variant. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown CacheControl: $json") + } + } + + internal class Deserializer : + BaseDeserializer(CacheControl::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): CacheControl { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl( + chatCompletionCachedContent = it, + _json = json, + ) + } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl(unionMember0 = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. + // deserializing from boolean). + 0 -> CacheControl(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, + // then use the first completely valid match, or simply the + // first match if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } + ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer(CacheControl::class) { + + override fun serialize( + value: CacheControl, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.unionMember0 != null -> + generator.writeObject(value.unionMember0) + value.chatCompletionCachedContent != null -> + generator.writeObject(value.chatCompletionCachedContent) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid CacheControl") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UnionMember0]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember0]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember0: UnionMember0) = apply { + additionalProperties = + unionMember0.additionalProperties.toMutableMap() + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember0]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): UnionMember0 = + UnionMember0(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember0 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember0 && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UnionMember0{additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionThinkingBlock && + type == other.type && + cacheControl == other.cacheControl && + signature == other.signature && + thinking == other.thinking && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, cacheControl, signature, thinking, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionThinkingBlock{type=$type, cacheControl=$cacheControl, signature=$signature, thinking=$thinking, additionalProperties=$additionalProperties}" + } + + class ChatCompletionRedactedThinkingBlock + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val cacheControl: JsonField, + private val data: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("data") + @ExcludeMissing + data: JsonField = JsonMissing.of(), + ) : this(type, cacheControl, data, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("redacted_thinking") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionRedactedThinkingBlock]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionRedactedThinkingBlock]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("redacted_thinking") + private var cacheControl: JsonField = JsonMissing.of() + private var data: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionRedactedThinkingBlock: ChatCompletionRedactedThinkingBlock + ) = apply { + type = chatCompletionRedactedThinkingBlock.type + cacheControl = chatCompletionRedactedThinkingBlock.cacheControl + data = chatCompletionRedactedThinkingBlock.data + additionalProperties = + chatCompletionRedactedThinkingBlock.additionalProperties + .toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults + * to the following: + * ```java + * JsonValue.from("redacted_thinking") + * ``` + * + * This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl?) = + cacheControl(JsonField.ofNullable(cacheControl)) + + /** + * Alias for calling [Builder.cacheControl] with + * `cacheControl.orElse(null)`. + */ + fun cacheControl(cacheControl: Optional) = + cacheControl(cacheControl.getOrNull()) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofUnionMember0(unionMember0)`. + */ + fun cacheControl(unionMember0: CacheControl.UnionMember0) = + cacheControl(CacheControl.ofUnionMember0(unionMember0)) + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofChatCompletionCachedContent()`. + */ + fun cacheControlChatCompletionCachedContent() = + cacheControl(CacheControl.ofChatCompletionCachedContent()) + + fun data(data: String) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionRedactedThinkingBlock]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ChatCompletionRedactedThinkingBlock = + ChatCompletionRedactedThinkingBlock( + type, + cacheControl, + data, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionRedactedThinkingBlock = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("redacted_thinking")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + data() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("redacted_thinking")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (if (data.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = CacheControl.Deserializer::class) + @JsonSerialize(using = CacheControl.Serializer::class) + class CacheControl + private constructor( + private val unionMember0: UnionMember0? = null, + private val chatCompletionCachedContent: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun unionMember0(): Optional = + Optional.ofNullable(unionMember0) + + fun chatCompletionCachedContent(): Optional = + Optional.ofNullable(chatCompletionCachedContent) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isChatCompletionCachedContent(): Boolean = + chatCompletionCachedContent != null + + fun asUnionMember0(): UnionMember0 = unionMember0.getOrThrow("unionMember0") + + fun asChatCompletionCachedContent(): JsonValue = + chatCompletionCachedContent.getOrThrow("chatCompletionCachedContent") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + unionMember0 != null -> visitor.visitUnionMember0(unionMember0) + chatCompletionCachedContent != null -> + visitor.visitChatCompletionCachedContent( + chatCompletionCachedContent + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) { + unionMember0.validate() + } + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) { + chatCompletionCachedContent.let { + if ( + it != JsonValue.from(mapOf("type" to "ephemeral")) + ) { + throw HanzoInvalidDataException( + "'chatCompletionCachedContent' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) = + unionMember0.validity() + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) = + chatCompletionCachedContent.let { + if (it == JsonValue.from(mapOf("type" to "ephemeral"))) + 1 + else 0 + } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + unionMember0 == other.unionMember0 && + chatCompletionCachedContent == other.chatCompletionCachedContent + } + + override fun hashCode(): Int = + Objects.hash(unionMember0, chatCompletionCachedContent) + + override fun toString(): String = + when { + unionMember0 != null -> "CacheControl{unionMember0=$unionMember0}" + chatCompletionCachedContent != null -> + "CacheControl{chatCompletionCachedContent=$chatCompletionCachedContent}" + _json != null -> "CacheControl{_unknown=$_json}" + else -> throw IllegalStateException("Invalid CacheControl") + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + CacheControl(unionMember0 = unionMember0) + + @JvmStatic + fun ofChatCompletionCachedContent() = + CacheControl( + chatCompletionCachedContent = + JsonValue.from(mapOf("type" to "ephemeral")) + ) + } + + /** + * An interface that defines how to map each variant of [CacheControl] to a + * value of type [T]. + */ + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ): T + + /** + * Maps an unknown variant of [CacheControl] to a value of type [T]. + * + * An instance of [CacheControl] can contain an unknown variant if it + * was deserialized from data that doesn't match any known variant. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown CacheControl: $json") + } + } + + internal class Deserializer : + BaseDeserializer(CacheControl::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): CacheControl { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl( + chatCompletionCachedContent = it, + _json = json, + ) + } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl(unionMember0 = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. + // deserializing from boolean). + 0 -> CacheControl(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, + // then use the first completely valid match, or simply the + // first match if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } + ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer(CacheControl::class) { + + override fun serialize( + value: CacheControl, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.unionMember0 != null -> + generator.writeObject(value.unionMember0) + value.chatCompletionCachedContent != null -> + generator.writeObject(value.chatCompletionCachedContent) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid CacheControl") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UnionMember0]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember0]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember0: UnionMember0) = apply { + additionalProperties = + unionMember0.additionalProperties.toMutableMap() + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember0]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): UnionMember0 = + UnionMember0(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember0 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember0 && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UnionMember0{additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionRedactedThinkingBlock && + type == other.type && + cacheControl == other.cacheControl && + data == other.data && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, cacheControl, data, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionRedactedThinkingBlock{type=$type, cacheControl=$cacheControl, data=$data, additionalProperties=$additionalProperties}" + } + } + + class ToolCall + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val id: JsonField, + private val function: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("function") + @ExcludeMissing + function: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + ) : this(id, function, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun function(): Function = function.getRequired("function") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("function") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [function]. + * + * Unlike [function], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function") + @ExcludeMissing + fun _function(): JsonField = function + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ToolCall]. + * + * The following fields are required: + * ```java + * .id() + * .function() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ToolCall]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var function: JsonField? = null + private var type: JsonValue = JsonValue.from("function") + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(toolCall: ToolCall) = apply { + id = toolCall.id + function = toolCall.function + type = toolCall.type + additionalProperties = toolCall.additionalProperties.toMutableMap() + } + + fun id(id: String?) = id(JsonField.ofNullable(id)) + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + fun function(function: Function) = function(JsonField.of(function)) + + /** + * Sets [Builder.function] to an arbitrary JSON value. + * + * You should usually call [Builder.function] with a well-typed [Function] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun function(function: JsonField) = apply { this.function = function } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("function") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ToolCall]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .function() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ToolCall = + ToolCall( + checkRequired("id", id), + checkRequired("function", function), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ToolCall = apply { + if (validated) { + return@apply + } + + id() + function().validate() + _type().let { + if (it != JsonValue.from("function")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (function.asKnown().getOrNull()?.validity() ?: 0) + + type.let { if (it == JsonValue.from("function")) 1 else 0 } + + class Function + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val arguments: JsonField, + private val name: JsonField, + private val providerSpecificFields: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("arguments") + @ExcludeMissing + arguments: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("provider_specific_fields") + @ExcludeMissing + providerSpecificFields: JsonField = JsonMissing.of(), + ) : this(arguments, name, providerSpecificFields, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun arguments(): Optional = arguments.getOptional("arguments") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun providerSpecificFields(): Optional = + providerSpecificFields.getOptional("provider_specific_fields") + + /** + * Returns the raw JSON value of [arguments]. + * + * Unlike [arguments], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("arguments") + @ExcludeMissing + fun _arguments(): JsonField = arguments + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [providerSpecificFields]. + * + * Unlike [providerSpecificFields], this method doesn't throw if the JSON field + * has an unexpected type. + */ + @JsonProperty("provider_specific_fields") + @ExcludeMissing + fun _providerSpecificFields(): JsonField = + providerSpecificFields + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Function]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var arguments: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var providerSpecificFields: JsonField = + JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + arguments = function.arguments + name = function.name + providerSpecificFields = function.providerSpecificFields + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun arguments(arguments: String) = arguments(JsonField.of(arguments)) + + /** + * Sets [Builder.arguments] to an arbitrary JSON value. + * + * You should usually call [Builder.arguments] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun arguments(arguments: JsonField) = apply { + this.arguments = arguments + } + + fun name(name: String?) = name(JsonField.ofNullable(name)) + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun providerSpecificFields( + providerSpecificFields: ProviderSpecificFields? + ) = providerSpecificFields(JsonField.ofNullable(providerSpecificFields)) + + /** + * Alias for calling [Builder.providerSpecificFields] with + * `providerSpecificFields.orElse(null)`. + */ + fun providerSpecificFields( + providerSpecificFields: Optional + ) = providerSpecificFields(providerSpecificFields.getOrNull()) + + /** + * Sets [Builder.providerSpecificFields] to an arbitrary JSON value. + * + * You should usually call [Builder.providerSpecificFields] with a + * well-typed [ProviderSpecificFields] value instead. This method is + * primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun providerSpecificFields( + providerSpecificFields: JsonField + ) = apply { this.providerSpecificFields = providerSpecificFields } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Function = + Function( + arguments, + name, + providerSpecificFields, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + arguments() + name() + providerSpecificFields().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (arguments.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (providerSpecificFields.asKnown().getOrNull()?.validity() ?: 0) + + class ProviderSpecificFields + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ProviderSpecificFields]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProviderSpecificFields]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(providerSpecificFields: ProviderSpecificFields) = + apply { + additionalProperties = + providerSpecificFields.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProviderSpecificFields]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): ProviderSpecificFields = + ProviderSpecificFields(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ProviderSpecificFields = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProviderSpecificFields && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProviderSpecificFields{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Function && + arguments == other.arguments && + name == other.name && + providerSpecificFields == other.providerSpecificFields && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(arguments, name, providerSpecificFields, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{arguments=$arguments, name=$name, providerSpecificFields=$providerSpecificFields, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ToolCall && + id == other.id && + function == other.function && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, function, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ToolCall{id=$id, function=$function, type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionAssistantMessage && + role == other.role && + cacheControl == other.cacheControl && + content == other.content && + functionCall == other.functionCall && + name == other.name && + reasoningContent == other.reasoningContent && + thinkingBlocks == other.thinkingBlocks && + toolCalls == other.toolCalls && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + role, + cacheControl, + content, + functionCall, + name, + reasoningContent, + thinkingBlocks, + toolCalls, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionAssistantMessage{role=$role, cacheControl=$cacheControl, content=$content, functionCall=$functionCall, name=$name, reasoningContent=$reasoningContent, thinkingBlocks=$thinkingBlocks, toolCalls=$toolCalls, additionalProperties=$additionalProperties}" + } + + class ChatCompletionToolMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val content: JsonField, + private val role: JsonValue, + private val toolCallId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("tool_call_id") + @ExcludeMissing + toolCallId: JsonField = JsonMissing.of(), + ) : this(content, role, toolCallId, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun content(): Content = content.getRequired("content") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("tool") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun toolCallId(): String = toolCallId.getRequired("tool_call_id") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [toolCallId]. + * + * Unlike [toolCallId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tool_call_id") + @ExcludeMissing + fun _toolCallId(): JsonField = toolCallId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionToolMessage]. + * + * The following fields are required: + * ```java + * .content() + * .toolCallId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionToolMessage]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var role: JsonValue = JsonValue.from("tool") + private var toolCallId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionToolMessage: ChatCompletionToolMessage) = apply { + content = chatCompletionToolMessage.content + role = chatCompletionToolMessage.role + toolCallId = chatCompletionToolMessage.toolCallId + additionalProperties = + chatCompletionToolMessage.additionalProperties.toMutableMap() + } + + fun content(content: Content) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** + * Alias for calling [content] with + * `Content.ofChatCompletionTextObjects(chatCompletionTextObjects)`. + */ + fun contentOfChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = content(Content.ofChatCompletionTextObjects(chatCompletionTextObjects)) + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("tool") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun toolCallId(toolCallId: String) = toolCallId(JsonField.of(toolCallId)) + + /** + * Sets [Builder.toolCallId] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCallId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun toolCallId(toolCallId: JsonField) = apply { + this.toolCallId = toolCallId + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionToolMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * .toolCallId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionToolMessage = + ChatCompletionToolMessage( + checkRequired("content", content), + role, + checkRequired("toolCallId", toolCallId), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionToolMessage = apply { + if (validated) { + return@apply + } + + content().validate() + _role().let { + if (it != JsonValue.from("tool")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + toolCallId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (content.asKnown().getOrNull()?.validity() ?: 0) + + role.let { if (it == JsonValue.from("tool")) 1 else 0 } + + (if (toolCallId.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val chatCompletionTextObjects: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun chatCompletionTextObjects(): Optional> = + Optional.ofNullable(chatCompletionTextObjects) + + fun isString(): Boolean = string != null + + fun isChatCompletionTextObjects(): Boolean = chatCompletionTextObjects != null + + fun asString(): String = string.getOrThrow("string") + + fun asChatCompletionTextObjects(): List = + chatCompletionTextObjects.getOrThrow("chatCompletionTextObjects") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + chatCompletionTextObjects != null -> + visitor.visitChatCompletionTextObjects(chatCompletionTextObjects) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ) { + chatCompletionTextObjects.forEach { it.validate() } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = chatCompletionTextObjects.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + chatCompletionTextObjects == other.chatCompletionTextObjects + } + + override fun hashCode(): Int = Objects.hash(string, chatCompletionTextObjects) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + chatCompletionTextObjects != null -> + "Content{chatCompletionTextObjects=$chatCompletionTextObjects}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = Content(chatCompletionTextObjects = chatCompletionTextObjects.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { + Content(chatCompletionTextObjects = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.chatCompletionTextObjects != null -> + generator.writeObject(value.chatCompletionTextObjects) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + + class ChatCompletionTextObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val text: JsonField, + private val type: JsonValue, + private val cacheControl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("text") + @ExcludeMissing + text: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + ) : this(text, type, cacheControl, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun text(): String = text.getRequired("text") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("text") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * Returns the raw JSON value of [text]. + * + * Unlike [text], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("text") @ExcludeMissing fun _text(): JsonField = text + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionTextObject]. + * + * The following fields are required: + * ```java + * .text() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionTextObject]. */ + class Builder internal constructor() { + + private var text: JsonField? = null + private var type: JsonValue = JsonValue.from("text") + private var cacheControl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionTextObject: ChatCompletionTextObject) = + apply { + text = chatCompletionTextObject.text + type = chatCompletionTextObject.type + cacheControl = chatCompletionTextObject.cacheControl + additionalProperties = + chatCompletionTextObject.additionalProperties.toMutableMap() + } + + fun text(text: String) = text(JsonField.of(text)) + + /** + * Sets [Builder.text] to an arbitrary JSON value. + * + * You should usually call [Builder.text] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun text(text: JsonField) = apply { this.text = text } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults + * to the following: + * ```java + * JsonValue.from("text") + * ``` + * + * This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionTextObject]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .text() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionTextObject = + ChatCompletionTextObject( + checkRequired("text", text), + type, + cacheControl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionTextObject = apply { + if (validated) { + return@apply + } + + text() + _type().let { + if (it != JsonValue.from("text")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (text.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("text")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [CacheControl]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = + cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionTextObject && + text == other.text && + type == other.type && + cacheControl == other.cacheControl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(text, type, cacheControl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionTextObject{text=$text, type=$type, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionToolMessage && + content == other.content && + role == other.role && + toolCallId == other.toolCallId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(content, role, toolCallId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionToolMessage{content=$content, role=$role, toolCallId=$toolCallId, additionalProperties=$additionalProperties}" + } + + class ChatCompletionSystemMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val content: JsonField, + private val role: JsonValue, + private val cacheControl: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(content, role, cacheControl, name, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun content(): Content = content.getRequired("content") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("system") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun cacheControl(): Optional = cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionSystemMessage]. + * + * The following fields are required: + * ```java + * .content() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionSystemMessage]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var role: JsonValue = JsonValue.from("system") + private var cacheControl: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionSystemMessage: ChatCompletionSystemMessage) = + apply { + content = chatCompletionSystemMessage.content + role = chatCompletionSystemMessage.role + cacheControl = chatCompletionSystemMessage.cacheControl + name = chatCompletionSystemMessage.name + additionalProperties = + chatCompletionSystemMessage.additionalProperties.toMutableMap() + } + + fun content(content: Content) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** Alias for calling [content] with `Content.ofJsonValues(jsonValues)`. */ + fun contentOfJsonValues(jsonValues: List) = + content(Content.ofJsonValues(jsonValues)) + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("system") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed [CacheControl] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionSystemMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionSystemMessage = + ChatCompletionSystemMessage( + checkRequired("content", content), + role, + cacheControl, + name, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionSystemMessage = apply { + if (validated) { + return@apply + } + + content().validate() + _role().let { + if (it != JsonValue.from("system")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (content.asKnown().getOrNull()?.validity() ?: 0) + + role.let { if (it == JsonValue.from("system")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val jsonValues: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun jsonValues(): Optional> = Optional.ofNullable(jsonValues) + + fun isString(): Boolean = string != null + + fun isJsonValues(): Boolean = jsonValues != null + + fun asString(): String = string.getOrThrow("string") + + fun asJsonValues(): List = jsonValues.getOrThrow("jsonValues") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + jsonValues != null -> visitor.visitJsonValues(jsonValues) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitJsonValues(jsonValues: List) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitJsonValues(jsonValues: List) = + jsonValues.size + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + jsonValues == other.jsonValues + } + + override fun hashCode(): Int = Objects.hash(string, jsonValues) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + jsonValues != null -> "Content{jsonValues=$jsonValues}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofJsonValues(jsonValues: List) = + Content(jsonValues = jsonValues.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitJsonValues(jsonValues: List): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Content(jsonValues = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.jsonValues != null -> generator.writeObject(value.jsonValues) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + } + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CacheControl]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionSystemMessage && + content == other.content && + role == other.role && + cacheControl == other.cacheControl && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(content, role, cacheControl, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionSystemMessage{content=$content, role=$role, cacheControl=$cacheControl, name=$name, additionalProperties=$additionalProperties}" + } + + class ChatCompletionFunctionMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val content: JsonField, + private val name: JsonField, + private val role: JsonValue, + private val toolCallId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("tool_call_id") + @ExcludeMissing + toolCallId: JsonField = JsonMissing.of(), + ) : this(content, name, role, toolCallId, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun name(): String = name.getRequired("name") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("function") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun toolCallId(): Optional = toolCallId.getOptional("tool_call_id") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [toolCallId]. + * + * Unlike [toolCallId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tool_call_id") + @ExcludeMissing + fun _toolCallId(): JsonField = toolCallId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionFunctionMessage]. + * + * The following fields are required: + * ```java + * .content() + * .name() + * .toolCallId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionFunctionMessage]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var name: JsonField? = null + private var role: JsonValue = JsonValue.from("function") + private var toolCallId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionFunctionMessage: ChatCompletionFunctionMessage) = + apply { + content = chatCompletionFunctionMessage.content + name = chatCompletionFunctionMessage.name + role = chatCompletionFunctionMessage.role + toolCallId = chatCompletionFunctionMessage.toolCallId + additionalProperties = + chatCompletionFunctionMessage.additionalProperties.toMutableMap() + } + + fun content(content: Content?) = content(JsonField.ofNullable(content)) + + /** Alias for calling [Builder.content] with `content.orElse(null)`. */ + fun content(content: Optional) = content(content.getOrNull()) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** + * Alias for calling [content] with + * `Content.ofChatCompletionTextObjects(chatCompletionTextObjects)`. + */ + fun contentOfChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = content(Content.ofChatCompletionTextObjects(chatCompletionTextObjects)) + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("function") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun toolCallId(toolCallId: String?) = toolCallId(JsonField.ofNullable(toolCallId)) + + /** Alias for calling [Builder.toolCallId] with `toolCallId.orElse(null)`. */ + fun toolCallId(toolCallId: Optional) = toolCallId(toolCallId.getOrNull()) + + /** + * Sets [Builder.toolCallId] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCallId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun toolCallId(toolCallId: JsonField) = apply { + this.toolCallId = toolCallId + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionFunctionMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * .name() + * .toolCallId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionFunctionMessage = + ChatCompletionFunctionMessage( + checkRequired("content", content), + checkRequired("name", name), + role, + checkRequired("toolCallId", toolCallId), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionFunctionMessage = apply { + if (validated) { + return@apply + } + + content().ifPresent { it.validate() } + name() + _role().let { + if (it != JsonValue.from("function")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + toolCallId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (content.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + role.let { if (it == JsonValue.from("function")) 1 else 0 } + + (if (toolCallId.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val chatCompletionTextObjects: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun chatCompletionTextObjects(): Optional> = + Optional.ofNullable(chatCompletionTextObjects) + + fun isString(): Boolean = string != null + + fun isChatCompletionTextObjects(): Boolean = chatCompletionTextObjects != null + + fun asString(): String = string.getOrThrow("string") + + fun asChatCompletionTextObjects(): List = + chatCompletionTextObjects.getOrThrow("chatCompletionTextObjects") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + chatCompletionTextObjects != null -> + visitor.visitChatCompletionTextObjects(chatCompletionTextObjects) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ) { + chatCompletionTextObjects.forEach { it.validate() } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = chatCompletionTextObjects.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + chatCompletionTextObjects == other.chatCompletionTextObjects + } + + override fun hashCode(): Int = Objects.hash(string, chatCompletionTextObjects) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + chatCompletionTextObjects != null -> + "Content{chatCompletionTextObjects=$chatCompletionTextObjects}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = Content(chatCompletionTextObjects = chatCompletionTextObjects.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { + Content(chatCompletionTextObjects = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.chatCompletionTextObjects != null -> + generator.writeObject(value.chatCompletionTextObjects) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + + class ChatCompletionTextObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val text: JsonField, + private val type: JsonValue, + private val cacheControl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("text") + @ExcludeMissing + text: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + ) : this(text, type, cacheControl, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun text(): String = text.getRequired("text") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("text") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * Returns the raw JSON value of [text]. + * + * Unlike [text], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("text") @ExcludeMissing fun _text(): JsonField = text + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionTextObject]. + * + * The following fields are required: + * ```java + * .text() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionTextObject]. */ + class Builder internal constructor() { + + private var text: JsonField? = null + private var type: JsonValue = JsonValue.from("text") + private var cacheControl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionTextObject: ChatCompletionTextObject) = + apply { + text = chatCompletionTextObject.text + type = chatCompletionTextObject.type + cacheControl = chatCompletionTextObject.cacheControl + additionalProperties = + chatCompletionTextObject.additionalProperties.toMutableMap() + } + + fun text(text: String) = text(JsonField.of(text)) + + /** + * Sets [Builder.text] to an arbitrary JSON value. + * + * You should usually call [Builder.text] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun text(text: JsonField) = apply { this.text = text } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults + * to the following: + * ```java + * JsonValue.from("text") + * ``` + * + * This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionTextObject]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .text() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionTextObject = + ChatCompletionTextObject( + checkRequired("text", text), + type, + cacheControl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionTextObject = apply { + if (validated) { + return@apply + } + + text() + _type().let { + if (it != JsonValue.from("text")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (text.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("text")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [CacheControl]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = + cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionTextObject && + text == other.text && + type == other.type && + cacheControl == other.cacheControl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(text, type, cacheControl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionTextObject{text=$text, type=$type, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionFunctionMessage && + content == other.content && + name == other.name && + role == other.role && + toolCallId == other.toolCallId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(content, name, role, toolCallId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionFunctionMessage{content=$content, name=$name, role=$role, toolCallId=$toolCallId, additionalProperties=$additionalProperties}" + } + + class ChatCompletionDeveloperMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val content: JsonField, + private val role: JsonValue, + private val cacheControl: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(content, role, cacheControl, name, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun content(): Content = content.getRequired("content") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("developer") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun cacheControl(): Optional = cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionDeveloperMessage]. + * + * The following fields are required: + * ```java + * .content() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionDeveloperMessage]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var role: JsonValue = JsonValue.from("developer") + private var cacheControl: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionDeveloperMessage: ChatCompletionDeveloperMessage) = + apply { + content = chatCompletionDeveloperMessage.content + role = chatCompletionDeveloperMessage.role + cacheControl = chatCompletionDeveloperMessage.cacheControl + name = chatCompletionDeveloperMessage.name + additionalProperties = + chatCompletionDeveloperMessage.additionalProperties.toMutableMap() + } + + fun content(content: Content) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** Alias for calling [content] with `Content.ofJsonValues(jsonValues)`. */ + fun contentOfJsonValues(jsonValues: List) = + content(Content.ofJsonValues(jsonValues)) + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("developer") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed [CacheControl] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionDeveloperMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionDeveloperMessage = + ChatCompletionDeveloperMessage( + checkRequired("content", content), + role, + cacheControl, + name, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionDeveloperMessage = apply { + if (validated) { + return@apply + } + + content().validate() + _role().let { + if (it != JsonValue.from("developer")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (content.asKnown().getOrNull()?.validity() ?: 0) + + role.let { if (it == JsonValue.from("developer")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val jsonValues: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun jsonValues(): Optional> = Optional.ofNullable(jsonValues) + + fun isString(): Boolean = string != null + + fun isJsonValues(): Boolean = jsonValues != null + + fun asString(): String = string.getOrThrow("string") + + fun asJsonValues(): List = jsonValues.getOrThrow("jsonValues") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + jsonValues != null -> visitor.visitJsonValues(jsonValues) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitJsonValues(jsonValues: List) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitJsonValues(jsonValues: List) = + jsonValues.size + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + jsonValues == other.jsonValues + } + + override fun hashCode(): Int = Objects.hash(string, jsonValues) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + jsonValues != null -> "Content{jsonValues=$jsonValues}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofJsonValues(jsonValues: List) = + Content(jsonValues = jsonValues.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitJsonValues(jsonValues: List): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Content(jsonValues = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.jsonValues != null -> generator.writeObject(value.jsonValues) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + } + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CacheControl]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionDeveloperMessage && + content == other.content && + role == other.role && + cacheControl == other.cacheControl && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(content, role, cacheControl, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionDeveloperMessage{content=$content, role=$role, cacheControl=$cacheControl, name=$name, additionalProperties=$additionalProperties}" + } + } + + class ContextWindowFallbackDict + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ContextWindowFallbackDict]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ContextWindowFallbackDict]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(contextWindowFallbackDict: ContextWindowFallbackDict) = apply { + additionalProperties = contextWindowFallbackDict.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ContextWindowFallbackDict]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ContextWindowFallbackDict = + ContextWindowFallbackDict(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ContextWindowFallbackDict = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ContextWindowFallbackDict && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ContextWindowFallbackDict{additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = FunctionCall.Deserializer::class) + @JsonSerialize(using = FunctionCall.Serializer::class) + class FunctionCall + private constructor( + private val string: String? = null, + private val unionMember1: UnionMember1? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun unionMember1(): Optional = Optional.ofNullable(unionMember1) + + fun isString(): Boolean = string != null + + fun isUnionMember1(): Boolean = unionMember1 != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnionMember1(): UnionMember1 = unionMember1.getOrThrow("unionMember1") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + unionMember1 != null -> visitor.visitUnionMember1(unionMember1) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): FunctionCall = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitUnionMember1(unionMember1: UnionMember1) { + unionMember1.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitUnionMember1(unionMember1: UnionMember1) = + unionMember1.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FunctionCall && + string == other.string && + unionMember1 == other.unionMember1 + } + + override fun hashCode(): Int = Objects.hash(string, unionMember1) + + override fun toString(): String = + when { + string != null -> "FunctionCall{string=$string}" + unionMember1 != null -> "FunctionCall{unionMember1=$unionMember1}" + _json != null -> "FunctionCall{_unknown=$_json}" + else -> throw IllegalStateException("Invalid FunctionCall") + } + + companion object { + + @JvmStatic fun ofString(string: String) = FunctionCall(string = string) + + @JvmStatic + fun ofUnionMember1(unionMember1: UnionMember1) = + FunctionCall(unionMember1 = unionMember1) + } + + /** + * An interface that defines how to map each variant of [FunctionCall] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitUnionMember1(unionMember1: UnionMember1): T + + /** + * Maps an unknown variant of [FunctionCall] to a value of type [T]. + * + * An instance of [FunctionCall] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown FunctionCall: $json") + } + } + + internal class Deserializer : BaseDeserializer(FunctionCall::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): FunctionCall { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionCall(unionMember1 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionCall(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> FunctionCall(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(FunctionCall::class) { + + override fun serialize( + value: FunctionCall, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unionMember1 != null -> generator.writeObject(value.unionMember1) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid FunctionCall") + } + } + } + + class UnionMember1 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UnionMember1]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember1]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember1: UnionMember1) = apply { + additionalProperties = unionMember1.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember1]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UnionMember1 = UnionMember1(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember1 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember1 && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "UnionMember1{additionalProperties=$additionalProperties}" + } + } + + class Function + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Function]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Function = Function(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Function && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Function{additionalProperties=$additionalProperties}" + } + + class LogitBias + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [LogitBias]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LogitBias]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(logitBias: LogitBias) = apply { + additionalProperties = logitBias.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [LogitBias]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): LogitBias = LogitBias(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): LogitBias = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is LogitBias && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "LogitBias{additionalProperties=$additionalProperties}" + } + + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + class ResponseFormat + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ResponseFormat]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseFormat]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseFormat: ResponseFormat) = apply { + additionalProperties = responseFormat.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ResponseFormat]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseFormat = ResponseFormat(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false - fun toBuilder() = Builder().from(this) + fun validate(): ResponseFormat = apply { + if (validated) { + return@apply + } - companion object { + validated = true + } - @JvmStatic fun none(): CompletionCreateParams = builder().build() + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } - /** Returns a mutable builder for constructing an instance of [CompletionCreateParams]. */ - @JvmStatic fun builder() = Builder() + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ResponseFormat && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseFormat{additionalProperties=$additionalProperties}" } - /** A builder for [CompletionCreateParams]. */ - class Builder internal constructor() { + @JsonDeserialize(using = Stop.Deserializer::class) + @JsonSerialize(using = Stop.Serializer::class) + class Stop + private constructor( + private val string: String? = null, + private val strings: List? = null, + private val _json: JsonValue? = null, + ) { - private var model: String? = null - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - private var additionalBodyProperties: MutableMap = mutableMapOf() + fun string(): Optional = Optional.ofNullable(string) - @JvmSynthetic - internal fun from(completionCreateParams: CompletionCreateParams) = apply { - model = completionCreateParams.model - additionalHeaders = completionCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = completionCreateParams.additionalQueryParams.toBuilder() - additionalBodyProperties = - completionCreateParams.additionalBodyProperties.toMutableMap() - } + fun strings(): Optional> = Optional.ofNullable(strings) - fun model(model: String?) = apply { this.model = model } + fun isString(): Boolean = string != null - /** Alias for calling [Builder.model] with `model.orElse(null)`. */ - fun model(model: Optional) = model(model.getOrNull()) + fun isStrings(): Boolean = strings != null - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Stop = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitStrings(strings: List) {} + } + ) + validated = true } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitStrings(strings: List) = strings.size + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Stop && string == other.string && strings == other.strings } - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Stop{string=$string}" + strings != null -> "Stop{strings=$strings}" + _json != null -> "Stop{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Stop") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Stop(string = string) + + @JvmStatic fun ofStrings(strings: List) = Stop(strings = strings.toImmutable()) } - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) + /** An interface that defines how to map each variant of [Stop] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + + /** + * Maps an unknown variant of [Stop] to a value of type [T]. + * + * An instance of [Stop] can contain an unknown variant if it was deserialized from data + * that doesn't match any known variant. For example, if the SDK is on an older version + * than the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Stop: $json") + } } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) + internal class Deserializer : BaseDeserializer(Stop::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Stop { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Stop(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Stop(strings = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> Stop(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } } - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) + internal class Serializer : BaseSerializer(Stop::class) { + + override fun serialize( + value: Stop, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.strings != null -> generator.writeObject(value.strings) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Stop") + } + } } + } - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) + class StreamOptions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [StreamOptions]. */ + @JvmStatic fun builder() = Builder() } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) + /** A builder for [StreamOptions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(streamOptions: StreamOptions) = apply { + additionalProperties = streamOptions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [StreamOptions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): StreamOptions = StreamOptions(additionalProperties.toImmutable()) } - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) + private var validated: Boolean = false + + fun validate(): StreamOptions = apply { + if (validated) { + return@apply + } + + validated = true } - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is StreamOptions && additionalProperties == other.additionalProperties } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) + override fun hashCode(): Int = hashCode + + override fun toString() = "StreamOptions{additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = ToolChoice.Deserializer::class) + @JsonSerialize(using = ToolChoice.Serializer::class) + class ToolChoice + private constructor( + private val string: String? = null, + private val unionMember1: UnionMember1? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun unionMember1(): Optional = Optional.ofNullable(unionMember1) + + fun isString(): Boolean = string != null + + fun isUnionMember1(): Boolean = unionMember1 != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnionMember1(): UnionMember1 = unionMember1.getOrThrow("unionMember1") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + unionMember1 != null -> visitor.visitUnionMember1(unionMember1) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): ToolChoice = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitUnionMember1(unionMember1: UnionMember1) { + unionMember1.validate() + } + } + ) + validated = true } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitUnionMember1(unionMember1: UnionMember1) = + unionMember1.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ToolChoice && + string == other.string && + unionMember1 == other.unionMember1 } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) + override fun hashCode(): Int = Objects.hash(string, unionMember1) + + override fun toString(): String = + when { + string != null -> "ToolChoice{string=$string}" + unionMember1 != null -> "ToolChoice{unionMember1=$unionMember1}" + _json != null -> "ToolChoice{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ToolChoice") + } + + companion object { + + @JvmStatic fun ofString(string: String) = ToolChoice(string = string) + + @JvmStatic + fun ofUnionMember1(unionMember1: UnionMember1) = ToolChoice(unionMember1 = unionMember1) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) + /** + * An interface that defines how to map each variant of [ToolChoice] to a value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitUnionMember1(unionMember1: UnionMember1): T + + /** + * Maps an unknown variant of [ToolChoice] to a value of type [T]. + * + * An instance of [ToolChoice] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown ToolChoice: $json") + } } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + internal class Deserializer : BaseDeserializer(ToolChoice::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): ToolChoice { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + ToolChoice(unionMember1 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + ToolChoice(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> ToolChoice(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) + internal class Serializer : BaseSerializer(ToolChoice::class) { + + override fun serialize( + value: ToolChoice, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unionMember1 != null -> generator.writeObject(value.unionMember1) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid ToolChoice") + } + } } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + class UnionMember1 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UnionMember1]. */ + @JvmStatic fun builder() = Builder() } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + /** A builder for [UnionMember1]. */ + class Builder internal constructor() { - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + private var additionalProperties: MutableMap = mutableMapOf() - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + @JvmSynthetic + internal fun from(unionMember1: UnionMember1) = apply { + additionalProperties = unionMember1.additionalProperties.toMutableMap() + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember1]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UnionMember1 = UnionMember1(additionalProperties.toImmutable()) } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + private var validated: Boolean = false - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + fun validate(): UnionMember1 = apply { + if (validated) { + return@apply + } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - putAllAdditionalBodyProperties(additionalBodyProperties) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember1 && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "UnionMember1{additionalProperties=$additionalProperties}" } + } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - additionalBodyProperties.put(key, value) + class Tool + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Tool]. */ + @JvmStatic fun builder() = Builder() } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) + /** A builder for [Tool]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(tool: Tool) = apply { + additionalProperties = tool.additionalProperties.toMutableMap() } - fun removeAdditionalBodyProperty(key: String) = apply { - additionalBodyProperties.remove(key) + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Tool]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Tool = Tool(additionalProperties.toImmutable()) } - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalBodyProperty) + private var validated: Boolean = false + + fun validate(): Tool = apply { + if (validated) { + return@apply + } + + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + /** - * Returns an immutable instance of [CompletionCreateParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * Further updates to this [Builder] will not mutate the returned instance. + * Used for best match union deserialization. */ - fun build(): CompletionCreateParams = - CompletionCreateParams( - model, - additionalHeaders.build(), - additionalQueryParams.build(), - additionalBodyProperties.toImmutable(), - ) - } + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - override fun _headers(): Headers = additionalHeaders + return other is Tool && additionalProperties == other.additionalProperties + } - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - model?.let { put("model", it) } - putAll(additionalQueryParams) - } - .build() + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Tool{additionalProperties=$additionalProperties}" + } override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is CompletionCreateParams && model == other.model && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is CompletionCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(model, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) override fun toString() = - "CompletionCreateParams{model=$model, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" + "CompletionCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/chat/completions/CompletionCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/chat/completions/CompletionCreateResponse.kt index 20dbeded..5d3dcfd9 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/chat/completions/CompletionCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/chat/completions/CompletionCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.chat.completions import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CompletionCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [CohereCreateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): CohereCreateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [CohereCreateParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = cohereCreateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [CohereCreateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): CohereCreateParams = CohereCreateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is CohereCreateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is CohereCreateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "CohereCreateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereCreateResponse.kt index b49c5d6e..f4d86092 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.cohere import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CohereCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [CohereDeleteParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): CohereDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [CohereDeleteParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = cohereDeleteParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [CohereDeleteParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): CohereDeleteParams = CohereDeleteParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is CohereDeleteParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is CohereDeleteParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "CohereDeleteParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereDeleteResponse.kt index 4fe2564e..884dd022 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.cohere import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CohereDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [CohereModifyParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): CohereModifyParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [CohereModifyParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = cohereModifyParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [CohereModifyParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): CohereModifyParams = CohereModifyParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is CohereModifyParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is CohereModifyParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "CohereModifyParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereModifyResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereModifyResponse.kt index 31021a1d..76d736cb 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereModifyResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereModifyResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.cohere import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CohereModifyResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(endpoint) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [CohereRetrieveParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): CohereRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [CohereRetrieveParams]. */ @JvmStatic fun builder() = Builder() } @@ -51,7 +49,10 @@ private constructor( additionalQueryParams = cohereRetrieveParams.additionalQueryParams.toBuilder() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -155,25 +156,14 @@ private constructor( * Returns an immutable instance of [CohereRetrieveParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): CohereRetrieveParams = - CohereRetrieveParams( - checkRequired("endpoint", endpoint), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + CohereRetrieveParams(endpoint, additionalHeaders.build(), additionalQueryParams.build()) } fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -186,10 +176,13 @@ private constructor( return true } - return /* spotless:off */ other is CohereRetrieveParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is CohereRetrieveParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(endpoint, additionalHeaders, additionalQueryParams) override fun toString() = "CohereRetrieveParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereRetrieveResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereRetrieveResponse.kt index 1e5d1bd9..8c3b95c5 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereRetrieveResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereRetrieveResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.cohere import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CohereRetrieveResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [CohereUpdateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): CohereUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [CohereUpdateParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = cohereUpdateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [CohereUpdateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): CohereUpdateParams = CohereUpdateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is CohereUpdateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is CohereUpdateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "CohereUpdateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereUpdateResponse.kt index 81cff2a4..e6ec5d81 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/cohere/CohereUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.cohere import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CohereUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(model) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -209,8 +212,7 @@ private constructor( ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) override fun _headers(): Headers = additionalHeaders @@ -228,10 +230,15 @@ private constructor( return true } - return /* spotless:off */ other is CompletionCreateParams && model == other.model && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is CompletionCreateParams && + model == other.model && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(model, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(model, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "CompletionCreateParams{model=$model, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/completions/CompletionCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/completions/CompletionCreateResponse.kt index b7633713..359d2f60 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/completions/CompletionCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/completions/CompletionCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.completions import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CompletionCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap = passThroughGenericEndpoint._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -182,7 +184,7 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): PassThroughGenericEndpoint = passThroughGenericEndpoint + fun _body(): PassThroughGenericEndpoint = passThroughGenericEndpoint override fun _headers(): Headers = additionalHeaders @@ -193,10 +195,14 @@ private constructor( return true } - return /* spotless:off */ other is PassThroughEndpointCreateParams && passThroughGenericEndpoint == other.passThroughGenericEndpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is PassThroughEndpointCreateParams && + passThroughGenericEndpoint == other.passThroughGenericEndpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(passThroughGenericEndpoint, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(passThroughGenericEndpoint, additionalHeaders, additionalQueryParams) override fun toString() = "PassThroughEndpointCreateParams{passThroughGenericEndpoint=$passThroughGenericEndpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointCreateResponse.kt index 337042b0..8beeb0e9 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.config.passthroughendpoint import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class PassThroughEndpointCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -86,17 +88,31 @@ private constructor(private val additionalProperties: MutableMap = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -210,8 +213,7 @@ private constructor( ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) override fun _headers(): Headers = additionalHeaders @@ -229,10 +231,15 @@ private constructor( return true } - return /* spotless:off */ other is PassThroughEndpointDeleteParams && endpointId == other.endpointId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is PassThroughEndpointDeleteParams && + endpointId == other.endpointId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpointId, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpointId, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "PassThroughEndpointDeleteParams{endpointId=$endpointId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointListParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointListParams.kt index 470e8768..99e6f70a 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointListParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointListParams.kt @@ -17,14 +17,19 @@ import kotlin.jvm.optionals.getOrNull class PassThroughEndpointListParams private constructor( private val endpointId: String?, + private val teamId: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { fun endpointId(): Optional = Optional.ofNullable(endpointId) + fun teamId(): Optional = Optional.ofNullable(teamId) + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -44,12 +49,14 @@ private constructor( class Builder internal constructor() { private var endpointId: String? = null + private var teamId: String? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(passThroughEndpointListParams: PassThroughEndpointListParams) = apply { endpointId = passThroughEndpointListParams.endpointId + teamId = passThroughEndpointListParams.teamId additionalHeaders = passThroughEndpointListParams.additionalHeaders.toBuilder() additionalQueryParams = passThroughEndpointListParams.additionalQueryParams.toBuilder() } @@ -59,6 +66,11 @@ private constructor( /** Alias for calling [Builder.endpointId] with `endpointId.orElse(null)`. */ fun endpointId(endpointId: Optional) = endpointId(endpointId.getOrNull()) + fun teamId(teamId: String?) = apply { this.teamId = teamId } + + /** Alias for calling [Builder.teamId] with `teamId.orElse(null)`. */ + fun teamId(teamId: Optional) = teamId(teamId.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() putAllAdditionalHeaders(additionalHeaders) @@ -165,6 +177,7 @@ private constructor( fun build(): PassThroughEndpointListParams = PassThroughEndpointListParams( endpointId, + teamId, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -176,6 +189,7 @@ private constructor( QueryParams.builder() .apply { endpointId?.let { put("endpoint_id", it) } + teamId?.let { put("team_id", it) } putAll(additionalQueryParams) } .build() @@ -185,11 +199,16 @@ private constructor( return true } - return /* spotless:off */ other is PassThroughEndpointListParams && endpointId == other.endpointId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is PassThroughEndpointListParams && + endpointId == other.endpointId && + teamId == other.teamId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpointId, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpointId, teamId, additionalHeaders, additionalQueryParams) override fun toString() = - "PassThroughEndpointListParams{endpointId=$endpointId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "PassThroughEndpointListParams{endpointId=$endpointId, teamId=$teamId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointResponse.kt index f929caad..b2199f79 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointResponse.kt @@ -16,8 +16,10 @@ import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.util.Collections import java.util.Objects +import kotlin.jvm.optionals.getOrNull class PassThroughEndpointResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val endpoints: JsonField>, private val additionalProperties: MutableMap, @@ -157,17 +159,34 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (endpoints.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is PassThroughEndpointResponse && endpoints == other.endpoints && additionalProperties == other.additionalProperties /* spotless:on */ + return other is PassThroughEndpointResponse && + endpoints == other.endpoints && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(endpoints, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointUpdateParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointUpdateParams.kt index 62c95a73..5c0c9d41 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointUpdateParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointUpdateParams.kt @@ -7,25 +7,30 @@ import ai.hanzo.api.core.Params import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.http.Headers import ai.hanzo.api.core.http.QueryParams -import ai.hanzo.api.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -/** Update a pass-through endpoint */ +/** Update a pass-through endpoint by ID. */ class PassThroughEndpointUpdateParams private constructor( - private val endpointId: String, + private val endpointId: String?, + private val passThroughGenericEndpoint: PassThroughGenericEndpoint, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, - private val additionalBodyProperties: Map, ) : Params { - fun endpointId(): String = endpointId + fun endpointId(): Optional = Optional.ofNullable(endpointId) - fun _additionalBodyProperties(): Map = additionalBodyProperties + fun passThroughGenericEndpoint(): PassThroughGenericEndpoint = passThroughGenericEndpoint + fun _additionalBodyProperties(): Map = + passThroughGenericEndpoint._additionalProperties() + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -38,7 +43,7 @@ private constructor( * * The following fields are required: * ```java - * .endpointId() + * .passThroughGenericEndpoint() * ``` */ @JvmStatic fun builder() = Builder() @@ -48,22 +53,30 @@ private constructor( class Builder internal constructor() { private var endpointId: String? = null + private var passThroughGenericEndpoint: PassThroughGenericEndpoint? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(passThroughEndpointUpdateParams: PassThroughEndpointUpdateParams) = apply { endpointId = passThroughEndpointUpdateParams.endpointId + passThroughGenericEndpoint = + passThroughEndpointUpdateParams.passThroughGenericEndpoint additionalHeaders = passThroughEndpointUpdateParams.additionalHeaders.toBuilder() additionalQueryParams = passThroughEndpointUpdateParams.additionalQueryParams.toBuilder() - additionalBodyProperties = - passThroughEndpointUpdateParams.additionalBodyProperties.toMutableMap() } - fun endpointId(endpointId: String) = apply { this.endpointId = endpointId } + fun endpointId(endpointId: String?) = apply { this.endpointId = endpointId } + + /** Alias for calling [Builder.endpointId] with `endpointId.orElse(null)`. */ + fun endpointId(endpointId: Optional) = endpointId(endpointId.getOrNull()) + + fun passThroughGenericEndpoint(passThroughGenericEndpoint: PassThroughGenericEndpoint) = + apply { + this.passThroughGenericEndpoint = passThroughGenericEndpoint + } fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -163,28 +176,6 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - putAllAdditionalBodyProperties(additionalBodyProperties) - } - - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - additionalBodyProperties.put(key, value) - } - - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - - fun removeAdditionalBodyProperty(key: String) = apply { - additionalBodyProperties.remove(key) - } - - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalBodyProperty) - } - /** * Returns an immutable instance of [PassThroughEndpointUpdateParams]. * @@ -192,27 +183,25 @@ private constructor( * * The following fields are required: * ```java - * .endpointId() + * .passThroughGenericEndpoint() * ``` * * @throws IllegalStateException if any required field is unset. */ fun build(): PassThroughEndpointUpdateParams = PassThroughEndpointUpdateParams( - checkRequired("endpointId", endpointId), + endpointId, + checkRequired("passThroughGenericEndpoint", passThroughGenericEndpoint), additionalHeaders.build(), additionalQueryParams.build(), - additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + fun _body(): PassThroughGenericEndpoint = passThroughGenericEndpoint fun _pathParam(index: Int): String = when (index) { - 0 -> endpointId + 0 -> endpointId ?: "" else -> "" } @@ -225,11 +214,21 @@ private constructor( return true } - return /* spotless:off */ other is PassThroughEndpointUpdateParams && endpointId == other.endpointId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is PassThroughEndpointUpdateParams && + endpointId == other.endpointId && + passThroughGenericEndpoint == other.passThroughGenericEndpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpointId, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + endpointId, + passThroughGenericEndpoint, + additionalHeaders, + additionalQueryParams, + ) override fun toString() = - "PassThroughEndpointUpdateParams{endpointId=$endpointId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" + "PassThroughEndpointUpdateParams{endpointId=$endpointId, passThroughGenericEndpoint=$passThroughGenericEndpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointUpdateResponse.kt index 677fd085..5cc0608d 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/config/passthroughendpoint/PassThroughEndpointUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.config.passthroughendpoint import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class PassThroughEndpointUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -86,17 +88,31 @@ private constructor(private val additionalProperties: MutableMap, private val target: JsonField, + private val id: JsonField, + private val auth: JsonField, + private val costPerRequest: JsonField, + private val guardrails: JsonField, + private val headers: JsonField, + private val includeSubpath: JsonField, private val additionalProperties: MutableMap, ) { @JsonCreator private constructor( - @JsonProperty("headers") @ExcludeMissing headers: JsonValue = JsonMissing.of(), @JsonProperty("path") @ExcludeMissing path: JsonField = JsonMissing.of(), @JsonProperty("target") @ExcludeMissing target: JsonField = JsonMissing.of(), - ) : this(headers, path, target, mutableMapOf()) + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("auth") @ExcludeMissing auth: JsonField = JsonMissing.of(), + @JsonProperty("cost_per_request") + @ExcludeMissing + costPerRequest: JsonField = JsonMissing.of(), + @JsonProperty("guardrails") + @ExcludeMissing + guardrails: JsonField = JsonMissing.of(), + @JsonProperty("headers") @ExcludeMissing headers: JsonField = JsonMissing.of(), + @JsonProperty("include_subpath") + @ExcludeMissing + includeSubpath: JsonField = JsonMissing.of(), + ) : this( + path, + target, + id, + auth, + costPerRequest, + guardrails, + headers, + includeSubpath, + mutableMapOf(), + ) /** - * Key-value pairs of headers to be forwarded with the request. You can set any key value pair - * here and it will be forwarded to your target endpoint - */ - @JsonProperty("headers") @ExcludeMissing fun _headers(): JsonValue = headers - - /** - * The route to be added to the LLM Proxy Server. + * The route to be added to the LiteLLM Proxy Server. * * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly * missing or null (e.g. if the server responded with an unexpected value). @@ -52,6 +76,62 @@ private constructor( */ fun target(): String = target.getRequired("target") + /** + * Optional unique identifier for the pass-through endpoint. If not provided, endpoints will be + * identified by path for backwards compatibility. + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Whether authentication is required for the pass-through endpoint. If True, requests to the + * endpoint will require a valid LiteLLM API key. + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun auth(): Optional = auth.getOptional("auth") + + /** + * The USD cost per request to the target endpoint. This is used to calculate the cost of the + * request to the target endpoint. + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun costPerRequest(): Optional = costPerRequest.getOptional("cost_per_request") + + /** + * Guardrails configuration for this passthrough endpoint. Dict keys are guardrail names, values + * are optional settings for field targeting. When set, all org/team/key level guardrails will + * also execute. Defaults to None (no guardrails execute). + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun guardrails(): Optional = guardrails.getOptional("guardrails") + + /** + * Key-value pairs of headers to be forwarded with the request. You can set any key value pair + * here and it will be forwarded to your target endpoint + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun headers(): Optional = headers.getOptional("headers") + + /** + * If True, requests to subpaths of the path will be forwarded to the target endpoint. For + * example, if the path is /bria and include_subpath is True, requests to + * /bria/v1/text-to-image/base/2.3 will be forwarded to the target endpoint. + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun includeSubpath(): Optional = includeSubpath.getOptional("include_subpath") + /** * Returns the raw JSON value of [path]. * @@ -66,6 +146,54 @@ private constructor( */ @JsonProperty("target") @ExcludeMissing fun _target(): JsonField = target + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [auth]. + * + * Unlike [auth], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("auth") @ExcludeMissing fun _auth(): JsonField = auth + + /** + * Returns the raw JSON value of [costPerRequest]. + * + * Unlike [costPerRequest], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("cost_per_request") + @ExcludeMissing + fun _costPerRequest(): JsonField = costPerRequest + + /** + * Returns the raw JSON value of [guardrails]. + * + * Unlike [guardrails], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("guardrails") + @ExcludeMissing + fun _guardrails(): JsonField = guardrails + + /** + * Returns the raw JSON value of [headers]. + * + * Unlike [headers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("headers") @ExcludeMissing fun _headers(): JsonField = headers + + /** + * Returns the raw JSON value of [includeSubpath]. + * + * Unlike [includeSubpath], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("include_subpath") + @ExcludeMissing + fun _includeSubpath(): JsonField = includeSubpath + @JsonAnySetter private fun putAdditionalProperty(key: String, value: JsonValue) { additionalProperties.put(key, value) @@ -85,7 +213,6 @@ private constructor( * * The following fields are required: * ```java - * .headers() * .path() * .target() * ``` @@ -96,26 +223,30 @@ private constructor( /** A builder for [PassThroughGenericEndpoint]. */ class Builder internal constructor() { - private var headers: JsonValue? = null private var path: JsonField? = null private var target: JsonField? = null + private var id: JsonField = JsonMissing.of() + private var auth: JsonField = JsonMissing.of() + private var costPerRequest: JsonField = JsonMissing.of() + private var guardrails: JsonField = JsonMissing.of() + private var headers: JsonField = JsonMissing.of() + private var includeSubpath: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(passThroughGenericEndpoint: PassThroughGenericEndpoint) = apply { - headers = passThroughGenericEndpoint.headers path = passThroughGenericEndpoint.path target = passThroughGenericEndpoint.target + id = passThroughGenericEndpoint.id + auth = passThroughGenericEndpoint.auth + costPerRequest = passThroughGenericEndpoint.costPerRequest + guardrails = passThroughGenericEndpoint.guardrails + headers = passThroughGenericEndpoint.headers + includeSubpath = passThroughGenericEndpoint.includeSubpath additionalProperties = passThroughGenericEndpoint.additionalProperties.toMutableMap() } - /** - * Key-value pairs of headers to be forwarded with the request. You can set any key value - * pair here and it will be forwarded to your target endpoint - */ - fun headers(headers: JsonValue) = apply { this.headers = headers } - - /** The route to be added to the LLM Proxy Server. */ + /** The route to be added to the LiteLLM Proxy Server. */ fun path(path: String) = path(JsonField.of(path)) /** @@ -137,6 +268,105 @@ private constructor( */ fun target(target: JsonField) = apply { this.target = target } + /** + * Optional unique identifier for the pass-through endpoint. If not provided, endpoints will + * be identified by path for backwards compatibility. + */ + fun id(id: String?) = id(JsonField.ofNullable(id)) + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** + * Whether authentication is required for the pass-through endpoint. If True, requests to + * the endpoint will require a valid LiteLLM API key. + */ + fun auth(auth: Boolean) = auth(JsonField.of(auth)) + + /** + * Sets [Builder.auth] to an arbitrary JSON value. + * + * You should usually call [Builder.auth] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun auth(auth: JsonField) = apply { this.auth = auth } + + /** + * The USD cost per request to the target endpoint. This is used to calculate the cost of + * the request to the target endpoint. + */ + fun costPerRequest(costPerRequest: Double) = costPerRequest(JsonField.of(costPerRequest)) + + /** + * Sets [Builder.costPerRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.costPerRequest] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun costPerRequest(costPerRequest: JsonField) = apply { + this.costPerRequest = costPerRequest + } + + /** + * Guardrails configuration for this passthrough endpoint. Dict keys are guardrail names, + * values are optional settings for field targeting. When set, all org/team/key level + * guardrails will also execute. Defaults to None (no guardrails execute). + */ + fun guardrails(guardrails: Guardrails?) = guardrails(JsonField.ofNullable(guardrails)) + + /** Alias for calling [Builder.guardrails] with `guardrails.orElse(null)`. */ + fun guardrails(guardrails: Optional) = guardrails(guardrails.getOrNull()) + + /** + * Sets [Builder.guardrails] to an arbitrary JSON value. + * + * You should usually call [Builder.guardrails] with a well-typed [Guardrails] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun guardrails(guardrails: JsonField) = apply { this.guardrails = guardrails } + + /** + * Key-value pairs of headers to be forwarded with the request. You can set any key value + * pair here and it will be forwarded to your target endpoint + */ + fun headers(headers: Headers) = headers(JsonField.of(headers)) + + /** + * Sets [Builder.headers] to an arbitrary JSON value. + * + * You should usually call [Builder.headers] with a well-typed [Headers] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun headers(headers: JsonField) = apply { this.headers = headers } + + /** + * If True, requests to subpaths of the path will be forwarded to the target endpoint. For + * example, if the path is /bria and include_subpath is True, requests to + * /bria/v1/text-to-image/base/2.3 will be forwarded to the target endpoint. + */ + fun includeSubpath(includeSubpath: Boolean) = includeSubpath(JsonField.of(includeSubpath)) + + /** + * Sets [Builder.includeSubpath] to an arbitrary JSON value. + * + * You should usually call [Builder.includeSubpath] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun includeSubpath(includeSubpath: JsonField) = apply { + this.includeSubpath = includeSubpath + } + fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() putAllAdditionalProperties(additionalProperties) @@ -163,7 +393,6 @@ private constructor( * * The following fields are required: * ```java - * .headers() * .path() * .target() * ``` @@ -172,9 +401,14 @@ private constructor( */ fun build(): PassThroughGenericEndpoint = PassThroughGenericEndpoint( - checkRequired("headers", headers), checkRequired("path", path), checkRequired("target", target), + id, + auth, + costPerRequest, + guardrails, + headers, + includeSubpath, additionalProperties.toMutableMap(), ) } @@ -188,23 +422,279 @@ private constructor( path() target() + id() + auth() + costPerRequest() + guardrails().ifPresent { it.validate() } + headers().ifPresent { it.validate() } + includeSubpath() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (path.asKnown().isPresent) 1 else 0) + + (if (target.asKnown().isPresent) 1 else 0) + + (if (id.asKnown().isPresent) 1 else 0) + + (if (auth.asKnown().isPresent) 1 else 0) + + (if (costPerRequest.asKnown().isPresent) 1 else 0) + + (guardrails.asKnown().getOrNull()?.validity() ?: 0) + + (headers.asKnown().getOrNull()?.validity() ?: 0) + + (if (includeSubpath.asKnown().isPresent) 1 else 0) + + /** + * Guardrails configuration for this passthrough endpoint. Dict keys are guardrail names, values + * are optional settings for field targeting. When set, all org/team/key level guardrails will + * also execute. Defaults to None (no guardrails execute). + */ + class Guardrails + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Guardrails]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Guardrails]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(guardrails: Guardrails) = apply { + additionalProperties = guardrails.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Guardrails]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Guardrails = Guardrails(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Guardrails = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Guardrails && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Guardrails{additionalProperties=$additionalProperties}" + } + + /** + * Key-value pairs of headers to be forwarded with the request. You can set any key value pair + * here and it will be forwarded to your target endpoint + */ + class Headers + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Headers]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Headers]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(headers: Headers) = apply { + additionalProperties = headers.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Headers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Headers = Headers(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Headers = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Headers && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Headers{additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is PassThroughGenericEndpoint && headers == other.headers && path == other.path && target == other.target && additionalProperties == other.additionalProperties /* spotless:on */ + return other is PassThroughGenericEndpoint && + path == other.path && + target == other.target && + id == other.id && + auth == other.auth && + costPerRequest == other.costPerRequest && + guardrails == other.guardrails && + headers == other.headers && + includeSubpath == other.includeSubpath && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(headers, path, target, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + path, + target, + id, + auth, + costPerRequest, + guardrails, + headers, + includeSubpath, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "PassThroughGenericEndpoint{headers=$headers, path=$path, target=$target, additionalProperties=$additionalProperties}" + "PassThroughGenericEndpoint{path=$path, target=$target, id=$id, auth=$auth, costPerRequest=$costPerRequest, guardrails=$guardrails, headers=$headers, includeSubpath=$includeSubpath, additionalProperties=$additionalProperties}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialCreateParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialCreateParams.kt index e50b3d89..f6af6cf2 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialCreateParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialCreateParams.kt @@ -10,6 +10,7 @@ import ai.hanzo.api.core.Params import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.http.Headers import ai.hanzo.api.core.http.QueryParams +import ai.hanzo.api.core.toImmutable import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter @@ -31,7 +32,11 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { - fun _credentialInfo(): JsonValue = body._credentialInfo() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun credentialInfo(): CredentialInfo = body.credentialInfo() /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly @@ -39,7 +44,11 @@ private constructor( */ fun credentialName(): String = body.credentialName() - fun _credentialValues(): JsonValue = body._credentialValues() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun credentialValues(): Optional = body.credentialValues() /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -47,6 +56,13 @@ private constructor( */ fun modelId(): Optional = body.modelId() + /** + * Returns the raw JSON value of [credentialInfo]. + * + * Unlike [credentialInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _credentialInfo(): JsonField = body._credentialInfo() + /** * Returns the raw JSON value of [credentialName]. * @@ -54,6 +70,14 @@ private constructor( */ fun _credentialName(): JsonField = body._credentialName() + /** + * Returns the raw JSON value of [credentialValues]. + * + * Unlike [credentialValues], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _credentialValues(): JsonField = body._credentialValues() + /** * Returns the raw JSON value of [modelId]. * @@ -63,8 +87,10 @@ private constructor( fun _additionalBodyProperties(): Map = body._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -97,7 +123,30 @@ private constructor( additionalQueryParams = credentialCreateParams.additionalQueryParams.toBuilder() } - fun credentialInfo(credentialInfo: JsonValue) = apply { + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [credentialInfo] + * - [credentialName] + * - [credentialValues] + * - [modelId] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + fun credentialInfo(credentialInfo: CredentialInfo) = apply { + body.credentialInfo(credentialInfo) + } + + /** + * Sets [Builder.credentialInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.credentialInfo] with a well-typed [CredentialInfo] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun credentialInfo(credentialInfo: JsonField) = apply { body.credentialInfo(credentialInfo) } @@ -114,7 +163,22 @@ private constructor( body.credentialName(credentialName) } - fun credentialValues(credentialValues: JsonValue) = apply { + fun credentialValues(credentialValues: CredentialValues?) = apply { + body.credentialValues(credentialValues) + } + + /** Alias for calling [Builder.credentialValues] with `credentialValues.orElse(null)`. */ + fun credentialValues(credentialValues: Optional) = + credentialValues(credentialValues.getOrNull()) + + /** + * Sets [Builder.credentialValues] to an arbitrary JSON value. + * + * You should usually call [Builder.credentialValues] with a well-typed [CredentialValues] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun credentialValues(credentialValues: JsonField) = apply { body.credentialValues(credentialValues) } @@ -269,17 +333,18 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): Body = body + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - private val credentialInfo: JsonValue, + private val credentialInfo: JsonField, private val credentialName: JsonField, - private val credentialValues: JsonValue, + private val credentialValues: JsonField, private val modelId: JsonField, private val additionalProperties: MutableMap, ) { @@ -288,19 +353,21 @@ private constructor( private constructor( @JsonProperty("credential_info") @ExcludeMissing - credentialInfo: JsonValue = JsonMissing.of(), + credentialInfo: JsonField = JsonMissing.of(), @JsonProperty("credential_name") @ExcludeMissing credentialName: JsonField = JsonMissing.of(), @JsonProperty("credential_values") @ExcludeMissing - credentialValues: JsonValue = JsonMissing.of(), + credentialValues: JsonField = JsonMissing.of(), @JsonProperty("model_id") @ExcludeMissing modelId: JsonField = JsonMissing.of(), ) : this(credentialInfo, credentialName, credentialValues, modelId, mutableMapOf()) - @JsonProperty("credential_info") - @ExcludeMissing - fun _credentialInfo(): JsonValue = credentialInfo + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun credentialInfo(): CredentialInfo = credentialInfo.getRequired("credential_info") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is @@ -308,15 +375,28 @@ private constructor( */ fun credentialName(): String = credentialName.getRequired("credential_name") - @JsonProperty("credential_values") - @ExcludeMissing - fun _credentialValues(): JsonValue = credentialValues + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun credentialValues(): Optional = + credentialValues.getOptional("credential_values") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun modelId(): Optional = Optional.ofNullable(modelId.getNullable("model_id")) + fun modelId(): Optional = modelId.getOptional("model_id") + + /** + * Returns the raw JSON value of [credentialInfo]. + * + * Unlike [credentialInfo], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("credential_info") + @ExcludeMissing + fun _credentialInfo(): JsonField = credentialInfo /** * Returns the raw JSON value of [credentialName]. @@ -328,6 +408,16 @@ private constructor( @ExcludeMissing fun _credentialName(): JsonField = credentialName + /** + * Returns the raw JSON value of [credentialValues]. + * + * Unlike [credentialValues], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("credential_values") + @ExcludeMissing + fun _credentialValues(): JsonField = credentialValues + /** * Returns the raw JSON value of [modelId]. * @@ -364,9 +454,9 @@ private constructor( /** A builder for [Body]. */ class Builder internal constructor() { - private var credentialInfo: JsonValue? = null + private var credentialInfo: JsonField? = null private var credentialName: JsonField? = null - private var credentialValues: JsonValue = JsonMissing.of() + private var credentialValues: JsonField = JsonMissing.of() private var modelId: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @@ -379,7 +469,17 @@ private constructor( additionalProperties = body.additionalProperties.toMutableMap() } - fun credentialInfo(credentialInfo: JsonValue) = apply { + fun credentialInfo(credentialInfo: CredentialInfo) = + credentialInfo(JsonField.of(credentialInfo)) + + /** + * Sets [Builder.credentialInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.credentialInfo] with a well-typed [CredentialInfo] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun credentialInfo(credentialInfo: JsonField) = apply { this.credentialInfo = credentialInfo } @@ -397,7 +497,23 @@ private constructor( this.credentialName = credentialName } - fun credentialValues(credentialValues: JsonValue) = apply { + fun credentialValues(credentialValues: CredentialValues?) = + credentialValues(JsonField.ofNullable(credentialValues)) + + /** + * Alias for calling [Builder.credentialValues] with `credentialValues.orElse(null)`. + */ + fun credentialValues(credentialValues: Optional) = + credentialValues(credentialValues.getOrNull()) + + /** + * Sets [Builder.credentialValues] to an arbitrary JSON value. + * + * You should usually call [Builder.credentialValues] with a well-typed + * [CredentialValues] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun credentialValues(credentialValues: JsonField) = apply { this.credentialValues = credentialValues } @@ -464,38 +580,273 @@ private constructor( return@apply } + credentialInfo().validate() credentialName() + credentialValues().ifPresent { it.validate() } modelId() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (credentialInfo.asKnown().getOrNull()?.validity() ?: 0) + + (if (credentialName.asKnown().isPresent) 1 else 0) + + (credentialValues.asKnown().getOrNull()?.validity() ?: 0) + + (if (modelId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && credentialInfo == other.credentialInfo && credentialName == other.credentialName && credentialValues == other.credentialValues && modelId == other.modelId && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Body && + credentialInfo == other.credentialInfo && + credentialName == other.credentialName && + credentialValues == other.credentialValues && + modelId == other.modelId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + credentialInfo, + credentialName, + credentialValues, + modelId, + additionalProperties, + ) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(credentialInfo, credentialName, credentialValues, modelId, additionalProperties) } - /* spotless:on */ - override fun hashCode(): Int = hashCode override fun toString() = "Body{credentialInfo=$credentialInfo, credentialName=$credentialName, credentialValues=$credentialValues, modelId=$modelId, additionalProperties=$additionalProperties}" } + class CredentialInfo + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CredentialInfo]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CredentialInfo]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(credentialInfo: CredentialInfo) = apply { + additionalProperties = credentialInfo.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CredentialInfo]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CredentialInfo = CredentialInfo(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): CredentialInfo = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CredentialInfo && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "CredentialInfo{additionalProperties=$additionalProperties}" + } + + class CredentialValues + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CredentialValues]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CredentialValues]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(credentialValues: CredentialValues) = apply { + additionalProperties = credentialValues.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CredentialValues]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CredentialValues = CredentialValues(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): CredentialValues = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CredentialValues && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "CredentialValues{additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is CredentialCreateParams && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is CredentialCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) override fun toString() = "CredentialCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialCreateResponse.kt index 8ea691de..5ac081d0 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.credentials import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CredentialCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun credentialName(): String = credentialName + /** The credential name, percent-decoded; may contain slashes */ + fun credentialName(): Optional = Optional.ofNullable(credentialName) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [CredentialDeleteParams]. - * - * The following fields are required: - * ```java - * .credentialName() - * ``` - */ + @JvmStatic fun none(): CredentialDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [CredentialDeleteParams]. */ @JvmStatic fun builder() = Builder() } @@ -60,7 +59,12 @@ private constructor( credentialDeleteParams.additionalBodyProperties.toMutableMap() } - fun credentialName(credentialName: String) = apply { this.credentialName = credentialName } + /** The credential name, percent-decoded; may contain slashes */ + fun credentialName(credentialName: String?) = apply { this.credentialName = credentialName } + + /** Alias for calling [Builder.credentialName] with `credentialName.orElse(null)`. */ + fun credentialName(credentialName: Optional) = + credentialName(credentialName.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -186,30 +190,22 @@ private constructor( * Returns an immutable instance of [CredentialDeleteParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .credentialName() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): CredentialDeleteParams = CredentialDeleteParams( - checkRequired("credentialName", credentialName), + credentialName, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> credentialName + 0 -> credentialName ?: "" else -> "" } @@ -222,10 +218,20 @@ private constructor( return true } - return /* spotless:off */ other is CredentialDeleteParams && credentialName == other.credentialName && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is CredentialDeleteParams && + credentialName == other.credentialName && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(credentialName, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + credentialName, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) override fun toString() = "CredentialDeleteParams{credentialName=$credentialName, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialDeleteResponse.kt index e214ff93..00597f9e 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.credentials import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CredentialDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, private val credentialName: JsonField, - private val credentialValues: JsonValue, + private val credentialValues: JsonField, private val additionalProperties: MutableMap, ) { @@ -27,18 +30,20 @@ private constructor( private constructor( @JsonProperty("credential_info") @ExcludeMissing - credentialInfo: JsonValue = JsonMissing.of(), + credentialInfo: JsonField = JsonMissing.of(), @JsonProperty("credential_name") @ExcludeMissing credentialName: JsonField = JsonMissing.of(), @JsonProperty("credential_values") @ExcludeMissing - credentialValues: JsonValue = JsonMissing.of(), + credentialValues: JsonField = JsonMissing.of(), ) : this(credentialInfo, credentialName, credentialValues, mutableMapOf()) - @JsonProperty("credential_info") - @ExcludeMissing - fun _credentialInfo(): JsonValue = credentialInfo + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun credentialInfo(): CredentialInfo = credentialInfo.getRequired("credential_info") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly @@ -46,9 +51,20 @@ private constructor( */ fun credentialName(): String = credentialName.getRequired("credential_name") - @JsonProperty("credential_values") + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun credentialValues(): CredentialValues = credentialValues.getRequired("credential_values") + + /** + * Returns the raw JSON value of [credentialInfo]. + * + * Unlike [credentialInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("credential_info") @ExcludeMissing - fun _credentialValues(): JsonValue = credentialValues + fun _credentialInfo(): JsonField = credentialInfo /** * Returns the raw JSON value of [credentialName]. @@ -59,6 +75,16 @@ private constructor( @ExcludeMissing fun _credentialName(): JsonField = credentialName + /** + * Returns the raw JSON value of [credentialValues]. + * + * Unlike [credentialValues], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("credential_values") + @ExcludeMissing + fun _credentialValues(): JsonField = credentialValues + @JsonAnySetter private fun putAdditionalProperty(key: String, value: JsonValue) { additionalProperties.put(key, value) @@ -89,9 +115,9 @@ private constructor( /** A builder for [CredentialItem]. */ class Builder internal constructor() { - private var credentialInfo: JsonValue? = null + private var credentialInfo: JsonField? = null private var credentialName: JsonField? = null - private var credentialValues: JsonValue? = null + private var credentialValues: JsonField? = null private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic @@ -102,7 +128,17 @@ private constructor( additionalProperties = credentialItem.additionalProperties.toMutableMap() } - fun credentialInfo(credentialInfo: JsonValue) = apply { + fun credentialInfo(credentialInfo: CredentialInfo) = + credentialInfo(JsonField.of(credentialInfo)) + + /** + * Sets [Builder.credentialInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.credentialInfo] with a well-typed [CredentialInfo] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun credentialInfo(credentialInfo: JsonField) = apply { this.credentialInfo = credentialInfo } @@ -119,7 +155,17 @@ private constructor( this.credentialName = credentialName } - fun credentialValues(credentialValues: JsonValue) = apply { + fun credentialValues(credentialValues: CredentialValues) = + credentialValues(JsonField.of(credentialValues)) + + /** + * Sets [Builder.credentialValues] to an arbitrary JSON value. + * + * You should usually call [Builder.credentialValues] with a well-typed [CredentialValues] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun credentialValues(credentialValues: JsonField) = apply { this.credentialValues = credentialValues } @@ -172,21 +218,244 @@ private constructor( return@apply } + credentialInfo().validate() credentialName() + credentialValues().validate() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (credentialInfo.asKnown().getOrNull()?.validity() ?: 0) + + (if (credentialName.asKnown().isPresent) 1 else 0) + + (credentialValues.asKnown().getOrNull()?.validity() ?: 0) + + class CredentialInfo + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CredentialInfo]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CredentialInfo]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(credentialInfo: CredentialInfo) = apply { + additionalProperties = credentialInfo.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CredentialInfo]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CredentialInfo = CredentialInfo(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): CredentialInfo = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CredentialInfo && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "CredentialInfo{additionalProperties=$additionalProperties}" + } + + class CredentialValues + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CredentialValues]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CredentialValues]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(credentialValues: CredentialValues) = apply { + additionalProperties = credentialValues.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CredentialValues]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CredentialValues = CredentialValues(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): CredentialValues = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CredentialValues && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "CredentialValues{additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is CredentialItem && credentialInfo == other.credentialInfo && credentialName == other.credentialName && credentialValues == other.credentialValues && additionalProperties == other.additionalProperties /* spotless:on */ + return other is CredentialItem && + credentialInfo == other.credentialInfo && + credentialName == other.credentialName && + credentialValues == other.credentialValues && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(credentialInfo, credentialName, credentialValues, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash(credentialInfo, credentialName, credentialValues, additionalProperties) + } override fun hashCode(): Int = hashCode diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialListParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialListParams.kt index b32cef87..4960b002 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialListParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialListParams.kt @@ -14,8 +14,10 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -156,10 +158,12 @@ private constructor( return true } - return /* spotless:off */ other is CredentialListParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is CredentialListParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(additionalHeaders, additionalQueryParams) override fun toString() = "CredentialListParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialListResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialListResponse.kt index b72467df..355918ae 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialListResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/credentials/CredentialListResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.credentials import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CredentialListResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap>, private val additionalProperties: MutableMap, @@ -154,17 +156,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (userIds.asKnown().getOrNull()?.size ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is BlockUsers && userIds == other.userIds && additionalProperties == other.additionalProperties /* spotless:on */ + return other is BlockUsers && + userIds == other.userIds && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(userIds, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerBlockParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerBlockParams.kt index 173a961a..4f7cb748 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerBlockParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerBlockParams.kt @@ -31,8 +31,10 @@ private constructor( fun _additionalBodyProperties(): Map = blockUsers._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -184,7 +186,7 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): BlockUsers = blockUsers + fun _body(): BlockUsers = blockUsers override fun _headers(): Headers = additionalHeaders @@ -195,10 +197,14 @@ private constructor( return true } - return /* spotless:off */ other is CustomerBlockParams && blockUsers == other.blockUsers && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is CustomerBlockParams && + blockUsers == other.blockUsers && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(blockUsers, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(blockUsers, additionalHeaders, additionalQueryParams) override fun toString() = "CustomerBlockParams{blockUsers=$blockUsers, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerBlockResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerBlockResponse.kt index b507c748..2bfca88a 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerBlockResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerBlockResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.customer import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CustomerBlockResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = body.budgetId() + /** + * Datetime when the budget is reset + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun budgetResetAt(): Optional = body.budgetResetAt() + /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). @@ -162,6 +173,12 @@ private constructor( */ fun softBudget(): Optional = body.softBudget() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spend(): Optional = body.spend() + /** * Max tokens per minute, allowed for this budget id. * @@ -213,6 +230,13 @@ private constructor( */ fun _budgetId(): JsonField = body._budgetId() + /** + * Returns the raw JSON value of [budgetResetAt]. + * + * Unlike [budgetResetAt], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _budgetResetAt(): JsonField = body._budgetResetAt() + /** * Returns the raw JSON value of [defaultModel]. * @@ -256,6 +280,13 @@ private constructor( */ fun _softBudget(): JsonField = body._softBudget() + /** + * Returns the raw JSON value of [spend]. + * + * Unlike [spend], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _spend(): JsonField = body._spend() + /** * Returns the raw JSON value of [tpmLimit]. * @@ -265,8 +296,10 @@ private constructor( fun _additionalBodyProperties(): Map = body._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -298,6 +331,20 @@ private constructor( additionalQueryParams = customerCreateParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [userId] + * - [alias] + * - [allowedModelRegion] + * - [blocked] + * - [budgetDuration] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun userId(userId: String) = apply { body.userId(userId) } /** @@ -383,6 +430,26 @@ private constructor( */ fun budgetId(budgetId: JsonField) = apply { body.budgetId(budgetId) } + /** Datetime when the budget is reset */ + fun budgetResetAt(budgetResetAt: OffsetDateTime?) = apply { + body.budgetResetAt(budgetResetAt) + } + + /** Alias for calling [Builder.budgetResetAt] with `budgetResetAt.orElse(null)`. */ + fun budgetResetAt(budgetResetAt: Optional) = + budgetResetAt(budgetResetAt.getOrNull()) + + /** + * Sets [Builder.budgetResetAt] to an arbitrary JSON value. + * + * You should usually call [Builder.budgetResetAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun budgetResetAt(budgetResetAt: JsonField) = apply { + body.budgetResetAt(budgetResetAt) + } + fun defaultModel(defaultModel: String?) = apply { body.defaultModel(defaultModel) } /** Alias for calling [Builder.defaultModel] with `defaultModel.orElse(null)`. */ @@ -517,6 +584,26 @@ private constructor( */ fun softBudget(softBudget: JsonField) = apply { body.softBudget(softBudget) } + fun spend(spend: Double?) = apply { body.spend(spend) } + + /** + * Alias for [Builder.spend]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun spend(spend: Double) = spend(spend as Double?) + + /** Alias for calling [Builder.spend] with `spend.orElse(null)`. */ + fun spend(spend: Optional) = spend(spend.getOrNull()) + + /** + * Sets [Builder.spend] to an arbitrary JSON value. + * + * You should usually call [Builder.spend] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun spend(spend: JsonField) = apply { body.spend(spend) } + /** Max tokens per minute, allowed for this budget id. */ fun tpmLimit(tpmLimit: Long?) = apply { body.tpmLimit(tpmLimit) } @@ -675,7 +762,7 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): Body = body + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders @@ -683,6 +770,7 @@ private constructor( /** Create a new customer, allocate a budget to them */ class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val userId: JsonField, private val alias: JsonField, @@ -690,12 +778,14 @@ private constructor( private val blocked: JsonField, private val budgetDuration: JsonField, private val budgetId: JsonField, + private val budgetResetAt: JsonField, private val defaultModel: JsonField, private val maxBudget: JsonField, private val maxParallelRequests: JsonField, private val modelMaxBudget: JsonField, private val rpmLimit: JsonField, private val softBudget: JsonField, + private val spend: JsonField, private val tpmLimit: JsonField, private val additionalProperties: MutableMap, ) { @@ -714,6 +804,9 @@ private constructor( @JsonProperty("budget_id") @ExcludeMissing budgetId: JsonField = JsonMissing.of(), + @JsonProperty("budget_reset_at") + @ExcludeMissing + budgetResetAt: JsonField = JsonMissing.of(), @JsonProperty("default_model") @ExcludeMissing defaultModel: JsonField = JsonMissing.of(), @@ -730,6 +823,7 @@ private constructor( @JsonProperty("soft_budget") @ExcludeMissing softBudget: JsonField = JsonMissing.of(), + @JsonProperty("spend") @ExcludeMissing spend: JsonField = JsonMissing.of(), @JsonProperty("tpm_limit") @ExcludeMissing tpmLimit: JsonField = JsonMissing.of(), ) : this( userId, @@ -738,12 +832,14 @@ private constructor( blocked, budgetDuration, budgetId, + budgetResetAt, defaultModel, maxBudget, maxParallelRequests, modelMaxBudget, rpmLimit, softBudget, + spend, tpmLimit, mutableMapOf(), ) @@ -758,20 +854,20 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun alias(): Optional = Optional.ofNullable(alias.getNullable("alias")) + fun alias(): Optional = alias.getOptional("alias") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun allowedModelRegion(): Optional = - Optional.ofNullable(allowedModelRegion.getNullable("allowed_model_region")) + allowedModelRegion.getOptional("allowed_model_region") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun blocked(): Optional = Optional.ofNullable(blocked.getNullable("blocked")) + fun blocked(): Optional = blocked.getOptional("blocked") /** * Max duration budget should be set for (e.g. '1hr', '1d', '28d') @@ -779,21 +875,27 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetDuration(): Optional = - Optional.ofNullable(budgetDuration.getNullable("budget_duration")) + fun budgetDuration(): Optional = budgetDuration.getOptional("budget_duration") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun budgetId(): Optional = budgetId.getOptional("budget_id") /** + * Datetime when the budget is reset + * * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetId(): Optional = Optional.ofNullable(budgetId.getNullable("budget_id")) + fun budgetResetAt(): Optional = budgetResetAt.getOptional("budget_reset_at") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun defaultModel(): Optional = - Optional.ofNullable(defaultModel.getNullable("default_model")) + fun defaultModel(): Optional = defaultModel.getOptional("default_model") /** * Requests will fail if this budget (in USD) is exceeded. @@ -801,7 +903,7 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun maxBudget(): Optional = Optional.ofNullable(maxBudget.getNullable("max_budget")) + fun maxBudget(): Optional = maxBudget.getOptional("max_budget") /** * Max concurrent requests allowed for this budget id. @@ -810,7 +912,7 @@ private constructor( * server responded with an unexpected value). */ fun maxParallelRequests(): Optional = - Optional.ofNullable(maxParallelRequests.getNullable("max_parallel_requests")) + maxParallelRequests.getOptional("max_parallel_requests") /** * Max budget for each model (e.g. {'gpt-4o': {'max_budget': '0.0000001', 'budget_duration': @@ -820,7 +922,7 @@ private constructor( * server responded with an unexpected value). */ fun modelMaxBudget(): Optional = - Optional.ofNullable(modelMaxBudget.getNullable("model_max_budget")) + modelMaxBudget.getOptional("model_max_budget") /** * Max requests per minute, allowed for this budget id. @@ -828,7 +930,7 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rpmLimit(): Optional = Optional.ofNullable(rpmLimit.getNullable("rpm_limit")) + fun rpmLimit(): Optional = rpmLimit.getOptional("rpm_limit") /** * Requests will NOT fail if this is exceeded. Will fire alerting though. @@ -836,8 +938,13 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun softBudget(): Optional = - Optional.ofNullable(softBudget.getNullable("soft_budget")) + fun softBudget(): Optional = softBudget.getOptional("soft_budget") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spend(): Optional = spend.getOptional("spend") /** * Max tokens per minute, allowed for this budget id. @@ -845,7 +952,7 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tpmLimit(): Optional = Optional.ofNullable(tpmLimit.getNullable("tpm_limit")) + fun tpmLimit(): Optional = tpmLimit.getOptional("tpm_limit") /** * Returns the raw JSON value of [userId]. @@ -895,6 +1002,16 @@ private constructor( */ @JsonProperty("budget_id") @ExcludeMissing fun _budgetId(): JsonField = budgetId + /** + * Returns the raw JSON value of [budgetResetAt]. + * + * Unlike [budgetResetAt], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("budget_reset_at") + @ExcludeMissing + fun _budgetResetAt(): JsonField = budgetResetAt + /** * Returns the raw JSON value of [defaultModel]. * @@ -948,6 +1065,13 @@ private constructor( @ExcludeMissing fun _softBudget(): JsonField = softBudget + /** + * Returns the raw JSON value of [spend]. + * + * Unlike [spend], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("spend") @ExcludeMissing fun _spend(): JsonField = spend + /** * Returns the raw JSON value of [tpmLimit]. * @@ -989,12 +1113,14 @@ private constructor( private var blocked: JsonField = JsonMissing.of() private var budgetDuration: JsonField = JsonMissing.of() private var budgetId: JsonField = JsonMissing.of() + private var budgetResetAt: JsonField = JsonMissing.of() private var defaultModel: JsonField = JsonMissing.of() private var maxBudget: JsonField = JsonMissing.of() private var maxParallelRequests: JsonField = JsonMissing.of() private var modelMaxBudget: JsonField = JsonMissing.of() private var rpmLimit: JsonField = JsonMissing.of() private var softBudget: JsonField = JsonMissing.of() + private var spend: JsonField = JsonMissing.of() private var tpmLimit: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @@ -1006,12 +1132,14 @@ private constructor( blocked = body.blocked budgetDuration = body.budgetDuration budgetId = body.budgetId + budgetResetAt = body.budgetResetAt defaultModel = body.defaultModel maxBudget = body.maxBudget maxParallelRequests = body.maxParallelRequests modelMaxBudget = body.modelMaxBudget rpmLimit = body.rpmLimit softBudget = body.softBudget + spend = body.spend tpmLimit = body.tpmLimit additionalProperties = body.additionalProperties.toMutableMap() } @@ -1106,6 +1234,25 @@ private constructor( */ fun budgetId(budgetId: JsonField) = apply { this.budgetId = budgetId } + /** Datetime when the budget is reset */ + fun budgetResetAt(budgetResetAt: OffsetDateTime?) = + budgetResetAt(JsonField.ofNullable(budgetResetAt)) + + /** Alias for calling [Builder.budgetResetAt] with `budgetResetAt.orElse(null)`. */ + fun budgetResetAt(budgetResetAt: Optional) = + budgetResetAt(budgetResetAt.getOrNull()) + + /** + * Sets [Builder.budgetResetAt] to an arbitrary JSON value. + * + * You should usually call [Builder.budgetResetAt] with a well-typed [OffsetDateTime] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun budgetResetAt(budgetResetAt: JsonField) = apply { + this.budgetResetAt = budgetResetAt + } + fun defaultModel(defaultModel: String?) = defaultModel(JsonField.ofNullable(defaultModel)) @@ -1242,6 +1389,27 @@ private constructor( */ fun softBudget(softBudget: JsonField) = apply { this.softBudget = softBudget } + fun spend(spend: Double?) = spend(JsonField.ofNullable(spend)) + + /** + * Alias for [Builder.spend]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun spend(spend: Double) = spend(spend as Double?) + + /** Alias for calling [Builder.spend] with `spend.orElse(null)`. */ + fun spend(spend: Optional) = spend(spend.getOrNull()) + + /** + * Sets [Builder.spend] to an arbitrary JSON value. + * + * You should usually call [Builder.spend] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spend(spend: JsonField) = apply { this.spend = spend } + /** Max tokens per minute, allowed for this budget id. */ fun tpmLimit(tpmLimit: Long?) = tpmLimit(JsonField.ofNullable(tpmLimit)) @@ -1303,12 +1471,14 @@ private constructor( blocked, budgetDuration, budgetId, + budgetResetAt, defaultModel, maxBudget, maxParallelRequests, modelMaxBudget, rpmLimit, softBudget, + spend, tpmLimit, additionalProperties.toMutableMap(), ) @@ -1323,36 +1493,103 @@ private constructor( userId() alias() - allowedModelRegion() + allowedModelRegion().ifPresent { it.validate() } blocked() budgetDuration() budgetId() + budgetResetAt() defaultModel() maxBudget() maxParallelRequests() modelMaxBudget().ifPresent { it.validate() } rpmLimit() softBudget() + spend() tpmLimit() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (userId.asKnown().isPresent) 1 else 0) + + (if (alias.asKnown().isPresent) 1 else 0) + + (allowedModelRegion.asKnown().getOrNull()?.validity() ?: 0) + + (if (blocked.asKnown().isPresent) 1 else 0) + + (if (budgetDuration.asKnown().isPresent) 1 else 0) + + (if (budgetId.asKnown().isPresent) 1 else 0) + + (if (budgetResetAt.asKnown().isPresent) 1 else 0) + + (if (defaultModel.asKnown().isPresent) 1 else 0) + + (if (maxBudget.asKnown().isPresent) 1 else 0) + + (if (maxParallelRequests.asKnown().isPresent) 1 else 0) + + (modelMaxBudget.asKnown().getOrNull()?.validity() ?: 0) + + (if (rpmLimit.asKnown().isPresent) 1 else 0) + + (if (softBudget.asKnown().isPresent) 1 else 0) + + (if (spend.asKnown().isPresent) 1 else 0) + + (if (tpmLimit.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && userId == other.userId && alias == other.alias && allowedModelRegion == other.allowedModelRegion && blocked == other.blocked && budgetDuration == other.budgetDuration && budgetId == other.budgetId && defaultModel == other.defaultModel && maxBudget == other.maxBudget && maxParallelRequests == other.maxParallelRequests && modelMaxBudget == other.modelMaxBudget && rpmLimit == other.rpmLimit && softBudget == other.softBudget && tpmLimit == other.tpmLimit && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Body && + userId == other.userId && + alias == other.alias && + allowedModelRegion == other.allowedModelRegion && + blocked == other.blocked && + budgetDuration == other.budgetDuration && + budgetId == other.budgetId && + budgetResetAt == other.budgetResetAt && + defaultModel == other.defaultModel && + maxBudget == other.maxBudget && + maxParallelRequests == other.maxParallelRequests && + modelMaxBudget == other.modelMaxBudget && + rpmLimit == other.rpmLimit && + softBudget == other.softBudget && + spend == other.spend && + tpmLimit == other.tpmLimit && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(userId, alias, allowedModelRegion, blocked, budgetDuration, budgetId, defaultModel, maxBudget, maxParallelRequests, modelMaxBudget, rpmLimit, softBudget, tpmLimit, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + userId, + alias, + allowedModelRegion, + blocked, + budgetDuration, + budgetId, + budgetResetAt, + defaultModel, + maxBudget, + maxParallelRequests, + modelMaxBudget, + rpmLimit, + softBudget, + spend, + tpmLimit, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "Body{userId=$userId, alias=$alias, allowedModelRegion=$allowedModelRegion, blocked=$blocked, budgetDuration=$budgetDuration, budgetId=$budgetId, defaultModel=$defaultModel, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, modelMaxBudget=$modelMaxBudget, rpmLimit=$rpmLimit, softBudget=$softBudget, tpmLimit=$tpmLimit, additionalProperties=$additionalProperties}" + "Body{userId=$userId, alias=$alias, allowedModelRegion=$allowedModelRegion, blocked=$blocked, budgetDuration=$budgetDuration, budgetId=$budgetId, budgetResetAt=$budgetResetAt, defaultModel=$defaultModel, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, modelMaxBudget=$modelMaxBudget, rpmLimit=$rpmLimit, softBudget=$softBudget, spend=$spend, tpmLimit=$tpmLimit, additionalProperties=$additionalProperties}" } class AllowedModelRegion @@ -1444,12 +1681,39 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AllowedModelRegion = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is AllowedModelRegion && value == other.value /* spotless:on */ + return other is AllowedModelRegion && value == other.value } override fun hashCode() = value.hashCode() @@ -1527,17 +1791,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is ModelMaxBudget && additionalProperties == other.additionalProperties /* spotless:on */ + return other is ModelMaxBudget && additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -1549,10 +1829,13 @@ private constructor( return true } - return /* spotless:off */ other is CustomerCreateParams && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is CustomerCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) override fun toString() = "CustomerCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerCreateResponse.kt index 49f7b11a..ef61c92a 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.customer import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CustomerCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = body._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -90,6 +93,15 @@ private constructor( additionalQueryParams = customerDeleteParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [userIds] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun userIds(userIds: List) = apply { body.userIds(userIds) } /** @@ -245,7 +257,7 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): Body = body + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders @@ -253,6 +265,7 @@ private constructor( /** Delete multiple Customers */ class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val userIds: JsonField>, private val additionalProperties: MutableMap, @@ -389,17 +402,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (userIds.asKnown().getOrNull()?.size ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && userIds == other.userIds && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Body && + userIds == other.userIds && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(userIds, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -412,10 +441,13 @@ private constructor( return true } - return /* spotless:off */ other is CustomerDeleteParams && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is CustomerDeleteParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) override fun toString() = "CustomerDeleteParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerDeleteResponse.kt index 67f21ae4..8ff72e29 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.customer import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CustomerDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, - private val userId: JsonField, - private val alias: JsonField, - private val allowedModelRegion: JsonField, - private val defaultModel: JsonField, - private val llmBudgetTable: JsonField, - private val spend: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("blocked") @ExcludeMissing blocked: JsonField = JsonMissing.of(), - @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), - @JsonProperty("alias") @ExcludeMissing alias: JsonField = JsonMissing.of(), - @JsonProperty("allowed_model_region") - @ExcludeMissing - allowedModelRegion: JsonField = JsonMissing.of(), - @JsonProperty("default_model") - @ExcludeMissing - defaultModel: JsonField = JsonMissing.of(), - @JsonProperty("llm_budget_table") - @ExcludeMissing - llmBudgetTable: JsonField = JsonMissing.of(), - @JsonProperty("spend") @ExcludeMissing spend: JsonField = JsonMissing.of(), - ) : this( - blocked, - userId, - alias, - allowedModelRegion, - defaultModel, - llmBudgetTable, - spend, - mutableMapOf(), - ) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly - * missing or null (e.g. if the server responded with an unexpected value). - */ - fun blocked(): Boolean = blocked.getRequired("blocked") - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly - * missing or null (e.g. if the server responded with an unexpected value). - */ - fun userId(): String = userId.getRequired("user_id") - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun alias(): Optional = Optional.ofNullable(alias.getNullable("alias")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun allowedModelRegion(): Optional = - Optional.ofNullable(allowedModelRegion.getNullable("allowed_model_region")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun defaultModel(): Optional = - Optional.ofNullable(defaultModel.getNullable("default_model")) - - /** - * Represents user-controllable params for a LLM_BudgetTable record - * - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun llmBudgetTable(): Optional = - Optional.ofNullable(llmBudgetTable.getNullable("llm_budget_table")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun spend(): Optional = Optional.ofNullable(spend.getNullable("spend")) - - /** - * Returns the raw JSON value of [blocked]. - * - * Unlike [blocked], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("blocked") @ExcludeMissing fun _blocked(): JsonField = blocked - - /** - * Returns the raw JSON value of [userId]. - * - * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId - - /** - * Returns the raw JSON value of [alias]. - * - * Unlike [alias], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("alias") @ExcludeMissing fun _alias(): JsonField = alias - - /** - * Returns the raw JSON value of [allowedModelRegion]. - * - * Unlike [allowedModelRegion], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("allowed_model_region") - @ExcludeMissing - fun _allowedModelRegion(): JsonField = allowedModelRegion - - /** - * Returns the raw JSON value of [defaultModel]. - * - * Unlike [defaultModel], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("default_model") - @ExcludeMissing - fun _defaultModel(): JsonField = defaultModel - - /** - * Returns the raw JSON value of [llmBudgetTable]. - * - * Unlike [llmBudgetTable], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("llm_budget_table") - @ExcludeMissing - fun _llmBudgetTable(): JsonField = llmBudgetTable - - /** - * Returns the raw JSON value of [spend]. - * - * Unlike [spend], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("spend") @ExcludeMissing fun _spend(): JsonField = spend - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [CustomerListResponse]. - * - * The following fields are required: - * ```java - * .blocked() - * .userId() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [CustomerListResponse]. */ - class Builder internal constructor() { - - private var blocked: JsonField? = null - private var userId: JsonField? = null - private var alias: JsonField = JsonMissing.of() - private var allowedModelRegion: JsonField = JsonMissing.of() - private var defaultModel: JsonField = JsonMissing.of() - private var llmBudgetTable: JsonField = JsonMissing.of() - private var spend: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(customerListResponse: CustomerListResponse) = apply { - blocked = customerListResponse.blocked - userId = customerListResponse.userId - alias = customerListResponse.alias - allowedModelRegion = customerListResponse.allowedModelRegion - defaultModel = customerListResponse.defaultModel - llmBudgetTable = customerListResponse.llmBudgetTable - spend = customerListResponse.spend - additionalProperties = customerListResponse.additionalProperties.toMutableMap() - } - - fun blocked(blocked: Boolean) = blocked(JsonField.of(blocked)) - - /** - * Sets [Builder.blocked] to an arbitrary JSON value. - * - * You should usually call [Builder.blocked] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun blocked(blocked: JsonField) = apply { this.blocked = blocked } - - fun userId(userId: String) = userId(JsonField.of(userId)) - - /** - * Sets [Builder.userId] to an arbitrary JSON value. - * - * You should usually call [Builder.userId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun userId(userId: JsonField) = apply { this.userId = userId } - - fun alias(alias: String?) = alias(JsonField.ofNullable(alias)) - - /** Alias for calling [Builder.alias] with `alias.orElse(null)`. */ - fun alias(alias: Optional) = alias(alias.getOrNull()) - - /** - * Sets [Builder.alias] to an arbitrary JSON value. - * - * You should usually call [Builder.alias] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun alias(alias: JsonField) = apply { this.alias = alias } - - fun allowedModelRegion(allowedModelRegion: AllowedModelRegion?) = - allowedModelRegion(JsonField.ofNullable(allowedModelRegion)) - - /** - * Alias for calling [Builder.allowedModelRegion] with `allowedModelRegion.orElse(null)`. - */ - fun allowedModelRegion(allowedModelRegion: Optional) = - allowedModelRegion(allowedModelRegion.getOrNull()) - - /** - * Sets [Builder.allowedModelRegion] to an arbitrary JSON value. - * - * You should usually call [Builder.allowedModelRegion] with a well-typed - * [AllowedModelRegion] value instead. This method is primarily for setting the field to an - * undocumented or not yet supported value. - */ - fun allowedModelRegion(allowedModelRegion: JsonField) = apply { - this.allowedModelRegion = allowedModelRegion - } - - fun defaultModel(defaultModel: String?) = defaultModel(JsonField.ofNullable(defaultModel)) - - /** Alias for calling [Builder.defaultModel] with `defaultModel.orElse(null)`. */ - fun defaultModel(defaultModel: Optional) = defaultModel(defaultModel.getOrNull()) - - /** - * Sets [Builder.defaultModel] to an arbitrary JSON value. - * - * You should usually call [Builder.defaultModel] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun defaultModel(defaultModel: JsonField) = apply { - this.defaultModel = defaultModel - } - - /** Represents user-controllable params for a LLM_BudgetTable record */ - fun llmBudgetTable(llmBudgetTable: LlmBudgetTable?) = - llmBudgetTable(JsonField.ofNullable(llmBudgetTable)) - - /** Alias for calling [Builder.llmBudgetTable] with `llmBudgetTable.orElse(null)`. */ - fun llmBudgetTable(llmBudgetTable: Optional) = - llmBudgetTable(llmBudgetTable.getOrNull()) - - /** - * Sets [Builder.llmBudgetTable] to an arbitrary JSON value. - * - * You should usually call [Builder.llmBudgetTable] with a well-typed [LlmBudgetTable] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun llmBudgetTable(llmBudgetTable: JsonField) = apply { - this.llmBudgetTable = llmBudgetTable - } - - fun spend(spend: Double) = spend(JsonField.of(spend)) - - /** - * Sets [Builder.spend] to an arbitrary JSON value. - * - * You should usually call [Builder.spend] with a well-typed [Double] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun spend(spend: JsonField) = apply { this.spend = spend } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [CustomerListResponse]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .blocked() - * .userId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): CustomerListResponse = - CustomerListResponse( - checkRequired("blocked", blocked), - checkRequired("userId", userId), - alias, - allowedModelRegion, - defaultModel, - llmBudgetTable, - spend, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): CustomerListResponse = apply { - if (validated) { - return@apply - } - - blocked() - userId() - alias() - allowedModelRegion() - defaultModel() - llmBudgetTable().ifPresent { it.validate() } - spend() - validated = true - } - - class AllowedModelRegion - @JsonCreator - private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val EU = of("eu") - - @JvmField val US = of("us") - - @JvmStatic fun of(value: String) = AllowedModelRegion(JsonField.of(value)) - } - - /** An enum containing [AllowedModelRegion]'s known values. */ - enum class Known { - EU, - US, - } - - /** - * An enum containing [AllowedModelRegion]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [AllowedModelRegion] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - EU, - US, - /** - * An enum member indicating that [AllowedModelRegion] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - EU -> Value.EU - US -> Value.US - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws HanzoInvalidDataException if this class instance's value is a not a known member. - */ - fun known(): Known = - when (this) { - EU -> Known.EU - US -> Known.US - else -> throw HanzoInvalidDataException("Unknown AllowedModelRegion: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws HanzoInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AllowedModelRegion && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** Represents user-controllable params for a LLM_BudgetTable record */ - class LlmBudgetTable - private constructor( - private val budgetDuration: JsonField, - private val maxBudget: JsonField, - private val maxParallelRequests: JsonField, - private val modelMaxBudget: JsonValue, - private val rpmLimit: JsonField, - private val softBudget: JsonField, - private val tpmLimit: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("budget_duration") - @ExcludeMissing - budgetDuration: JsonField = JsonMissing.of(), - @JsonProperty("max_budget") - @ExcludeMissing - maxBudget: JsonField = JsonMissing.of(), - @JsonProperty("max_parallel_requests") - @ExcludeMissing - maxParallelRequests: JsonField = JsonMissing.of(), - @JsonProperty("model_max_budget") - @ExcludeMissing - modelMaxBudget: JsonValue = JsonMissing.of(), - @JsonProperty("rpm_limit") @ExcludeMissing rpmLimit: JsonField = JsonMissing.of(), - @JsonProperty("soft_budget") - @ExcludeMissing - softBudget: JsonField = JsonMissing.of(), - @JsonProperty("tpm_limit") @ExcludeMissing tpmLimit: JsonField = JsonMissing.of(), - ) : this( - budgetDuration, - maxBudget, - maxParallelRequests, - modelMaxBudget, - rpmLimit, - softBudget, - tpmLimit, - mutableMapOf(), - ) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun budgetDuration(): Optional = - Optional.ofNullable(budgetDuration.getNullable("budget_duration")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun maxBudget(): Optional = Optional.ofNullable(maxBudget.getNullable("max_budget")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun maxParallelRequests(): Optional = - Optional.ofNullable(maxParallelRequests.getNullable("max_parallel_requests")) - - @JsonProperty("model_max_budget") - @ExcludeMissing - fun _modelMaxBudget(): JsonValue = modelMaxBudget - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun rpmLimit(): Optional = Optional.ofNullable(rpmLimit.getNullable("rpm_limit")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun softBudget(): Optional = - Optional.ofNullable(softBudget.getNullable("soft_budget")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun tpmLimit(): Optional = Optional.ofNullable(tpmLimit.getNullable("tpm_limit")) - - /** - * Returns the raw JSON value of [budgetDuration]. - * - * Unlike [budgetDuration], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("budget_duration") - @ExcludeMissing - fun _budgetDuration(): JsonField = budgetDuration - - /** - * Returns the raw JSON value of [maxBudget]. - * - * Unlike [maxBudget], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("max_budget") @ExcludeMissing fun _maxBudget(): JsonField = maxBudget - - /** - * Returns the raw JSON value of [maxParallelRequests]. - * - * Unlike [maxParallelRequests], this method doesn't throw if the JSON field has an - * unexpected type. - */ - @JsonProperty("max_parallel_requests") - @ExcludeMissing - fun _maxParallelRequests(): JsonField = maxParallelRequests - - /** - * Returns the raw JSON value of [rpmLimit]. - * - * Unlike [rpmLimit], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("rpm_limit") @ExcludeMissing fun _rpmLimit(): JsonField = rpmLimit - - /** - * Returns the raw JSON value of [softBudget]. - * - * Unlike [softBudget], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("soft_budget") - @ExcludeMissing - fun _softBudget(): JsonField = softBudget - - /** - * Returns the raw JSON value of [tpmLimit]. - * - * Unlike [tpmLimit], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("tpm_limit") @ExcludeMissing fun _tpmLimit(): JsonField = tpmLimit - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [LlmBudgetTable]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [LlmBudgetTable]. */ - class Builder internal constructor() { - - private var budgetDuration: JsonField = JsonMissing.of() - private var maxBudget: JsonField = JsonMissing.of() - private var maxParallelRequests: JsonField = JsonMissing.of() - private var modelMaxBudget: JsonValue = JsonMissing.of() - private var rpmLimit: JsonField = JsonMissing.of() - private var softBudget: JsonField = JsonMissing.of() - private var tpmLimit: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(llmBudgetTable: LlmBudgetTable) = apply { - budgetDuration = llmBudgetTable.budgetDuration - maxBudget = llmBudgetTable.maxBudget - maxParallelRequests = llmBudgetTable.maxParallelRequests - modelMaxBudget = llmBudgetTable.modelMaxBudget - rpmLimit = llmBudgetTable.rpmLimit - softBudget = llmBudgetTable.softBudget - tpmLimit = llmBudgetTable.tpmLimit - additionalProperties = llmBudgetTable.additionalProperties.toMutableMap() - } - - fun budgetDuration(budgetDuration: String?) = - budgetDuration(JsonField.ofNullable(budgetDuration)) - - /** Alias for calling [Builder.budgetDuration] with `budgetDuration.orElse(null)`. */ - fun budgetDuration(budgetDuration: Optional) = - budgetDuration(budgetDuration.getOrNull()) - - /** - * Sets [Builder.budgetDuration] to an arbitrary JSON value. - * - * You should usually call [Builder.budgetDuration] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun budgetDuration(budgetDuration: JsonField) = apply { - this.budgetDuration = budgetDuration - } - - fun maxBudget(maxBudget: Double?) = maxBudget(JsonField.ofNullable(maxBudget)) - - /** - * Alias for [Builder.maxBudget]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun maxBudget(maxBudget: Double) = maxBudget(maxBudget as Double?) - - /** Alias for calling [Builder.maxBudget] with `maxBudget.orElse(null)`. */ - fun maxBudget(maxBudget: Optional) = maxBudget(maxBudget.getOrNull()) - - /** - * Sets [Builder.maxBudget] to an arbitrary JSON value. - * - * You should usually call [Builder.maxBudget] with a well-typed [Double] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxBudget(maxBudget: JsonField) = apply { this.maxBudget = maxBudget } - - fun maxParallelRequests(maxParallelRequests: Long?) = - maxParallelRequests(JsonField.ofNullable(maxParallelRequests)) - - /** - * Alias for [Builder.maxParallelRequests]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun maxParallelRequests(maxParallelRequests: Long) = - maxParallelRequests(maxParallelRequests as Long?) - - /** - * Alias for calling [Builder.maxParallelRequests] with - * `maxParallelRequests.orElse(null)`. - */ - fun maxParallelRequests(maxParallelRequests: Optional) = - maxParallelRequests(maxParallelRequests.getOrNull()) - - /** - * Sets [Builder.maxParallelRequests] to an arbitrary JSON value. - * - * You should usually call [Builder.maxParallelRequests] with a well-typed [Long] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxParallelRequests(maxParallelRequests: JsonField) = apply { - this.maxParallelRequests = maxParallelRequests - } - - fun modelMaxBudget(modelMaxBudget: JsonValue) = apply { - this.modelMaxBudget = modelMaxBudget - } - - fun rpmLimit(rpmLimit: Long?) = rpmLimit(JsonField.ofNullable(rpmLimit)) - - /** - * Alias for [Builder.rpmLimit]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun rpmLimit(rpmLimit: Long) = rpmLimit(rpmLimit as Long?) - - /** Alias for calling [Builder.rpmLimit] with `rpmLimit.orElse(null)`. */ - fun rpmLimit(rpmLimit: Optional) = rpmLimit(rpmLimit.getOrNull()) - - /** - * Sets [Builder.rpmLimit] to an arbitrary JSON value. - * - * You should usually call [Builder.rpmLimit] with a well-typed [Long] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun rpmLimit(rpmLimit: JsonField) = apply { this.rpmLimit = rpmLimit } - - fun softBudget(softBudget: Double?) = softBudget(JsonField.ofNullable(softBudget)) - - /** - * Alias for [Builder.softBudget]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun softBudget(softBudget: Double) = softBudget(softBudget as Double?) - - /** Alias for calling [Builder.softBudget] with `softBudget.orElse(null)`. */ - fun softBudget(softBudget: Optional) = softBudget(softBudget.getOrNull()) - - /** - * Sets [Builder.softBudget] to an arbitrary JSON value. - * - * You should usually call [Builder.softBudget] with a well-typed [Double] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun softBudget(softBudget: JsonField) = apply { this.softBudget = softBudget } - - fun tpmLimit(tpmLimit: Long?) = tpmLimit(JsonField.ofNullable(tpmLimit)) - - /** - * Alias for [Builder.tpmLimit]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun tpmLimit(tpmLimit: Long) = tpmLimit(tpmLimit as Long?) - - /** Alias for calling [Builder.tpmLimit] with `tpmLimit.orElse(null)`. */ - fun tpmLimit(tpmLimit: Optional) = tpmLimit(tpmLimit.getOrNull()) - - /** - * Sets [Builder.tpmLimit] to an arbitrary JSON value. - * - * You should usually call [Builder.tpmLimit] with a well-typed [Long] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun tpmLimit(tpmLimit: JsonField) = apply { this.tpmLimit = tpmLimit } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [LlmBudgetTable]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): LlmBudgetTable = - LlmBudgetTable( - budgetDuration, - maxBudget, - maxParallelRequests, - modelMaxBudget, - rpmLimit, - softBudget, - tpmLimit, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): LlmBudgetTable = apply { - if (validated) { - return@apply - } - - budgetDuration() - maxBudget() - maxParallelRequests() - rpmLimit() - softBudget() - tpmLimit() - validated = true - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is LlmBudgetTable && budgetDuration == other.budgetDuration && maxBudget == other.maxBudget && maxParallelRequests == other.maxParallelRequests && modelMaxBudget == other.modelMaxBudget && rpmLimit == other.rpmLimit && softBudget == other.softBudget && tpmLimit == other.tpmLimit && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(budgetDuration, maxBudget, maxParallelRequests, modelMaxBudget, rpmLimit, softBudget, tpmLimit, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "LlmBudgetTable{budgetDuration=$budgetDuration, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, modelMaxBudget=$modelMaxBudget, rpmLimit=$rpmLimit, softBudget=$softBudget, tpmLimit=$tpmLimit, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is CustomerListResponse && blocked == other.blocked && userId == other.userId && alias == other.alias && allowedModelRegion == other.allowedModelRegion && defaultModel == other.defaultModel && llmBudgetTable == other.llmBudgetTable && spend == other.spend && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(blocked, userId, alias, allowedModelRegion, defaultModel, llmBudgetTable, spend, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "CustomerListResponse{blocked=$blocked, userId=$userId, alias=$alias, allowedModelRegion=$allowedModelRegion, defaultModel=$defaultModel, llmBudgetTable=$llmBudgetTable, spend=$spend, additionalProperties=$additionalProperties}" -} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerRetrieveInfoParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerRetrieveInfoParams.kt index d8e58ce8..7fed74cd 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerRetrieveInfoParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerRetrieveInfoParams.kt @@ -16,7 +16,7 @@ import java.util.Objects * * Example curl: * ``` - * curl -X GET 'http://localhost:4000/customer/info?end_user_id=test-llm-user-4' -H 'Authorization: Bearer sk-1234' + * curl -X GET 'http://localhost:4000/customer/info?end_user_id=test-litellm-user-4' -H 'Authorization: Bearer sk-1234' * ``` */ class CustomerRetrieveInfoParams @@ -29,8 +29,10 @@ private constructor( /** End User ID in the request parameters */ fun endUserId(): String = endUserId + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -198,10 +200,13 @@ private constructor( return true } - return /* spotless:off */ other is CustomerRetrieveInfoParams && endUserId == other.endUserId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is CustomerRetrieveInfoParams && + endUserId == other.endUserId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endUserId, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(endUserId, additionalHeaders, additionalQueryParams) override fun toString() = "CustomerRetrieveInfoParams{endUserId=$endUserId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerRetrieveInfoResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerRetrieveInfoResponse.kt deleted file mode 100644 index 9c02a8ea..00000000 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerRetrieveInfoResponse.kt +++ /dev/null @@ -1,874 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package ai.hanzo.api.models.customer - -import ai.hanzo.api.core.Enum -import ai.hanzo.api.core.ExcludeMissing -import ai.hanzo.api.core.JsonField -import ai.hanzo.api.core.JsonMissing -import ai.hanzo.api.core.JsonValue -import ai.hanzo.api.core.checkRequired -import ai.hanzo.api.errors.HanzoInvalidDataException -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import java.util.Collections -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -class CustomerRetrieveInfoResponse -private constructor( - private val blocked: JsonField, - private val userId: JsonField, - private val alias: JsonField, - private val allowedModelRegion: JsonField, - private val defaultModel: JsonField, - private val llmBudgetTable: JsonField, - private val spend: JsonField, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("blocked") @ExcludeMissing blocked: JsonField = JsonMissing.of(), - @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), - @JsonProperty("alias") @ExcludeMissing alias: JsonField = JsonMissing.of(), - @JsonProperty("allowed_model_region") - @ExcludeMissing - allowedModelRegion: JsonField = JsonMissing.of(), - @JsonProperty("default_model") - @ExcludeMissing - defaultModel: JsonField = JsonMissing.of(), - @JsonProperty("llm_budget_table") - @ExcludeMissing - llmBudgetTable: JsonField = JsonMissing.of(), - @JsonProperty("spend") @ExcludeMissing spend: JsonField = JsonMissing.of(), - ) : this( - blocked, - userId, - alias, - allowedModelRegion, - defaultModel, - llmBudgetTable, - spend, - mutableMapOf(), - ) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly - * missing or null (e.g. if the server responded with an unexpected value). - */ - fun blocked(): Boolean = blocked.getRequired("blocked") - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly - * missing or null (e.g. if the server responded with an unexpected value). - */ - fun userId(): String = userId.getRequired("user_id") - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun alias(): Optional = Optional.ofNullable(alias.getNullable("alias")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun allowedModelRegion(): Optional = - Optional.ofNullable(allowedModelRegion.getNullable("allowed_model_region")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun defaultModel(): Optional = - Optional.ofNullable(defaultModel.getNullable("default_model")) - - /** - * Represents user-controllable params for a LLM_BudgetTable record - * - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun llmBudgetTable(): Optional = - Optional.ofNullable(llmBudgetTable.getNullable("llm_budget_table")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun spend(): Optional = Optional.ofNullable(spend.getNullable("spend")) - - /** - * Returns the raw JSON value of [blocked]. - * - * Unlike [blocked], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("blocked") @ExcludeMissing fun _blocked(): JsonField = blocked - - /** - * Returns the raw JSON value of [userId]. - * - * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId - - /** - * Returns the raw JSON value of [alias]. - * - * Unlike [alias], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("alias") @ExcludeMissing fun _alias(): JsonField = alias - - /** - * Returns the raw JSON value of [allowedModelRegion]. - * - * Unlike [allowedModelRegion], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("allowed_model_region") - @ExcludeMissing - fun _allowedModelRegion(): JsonField = allowedModelRegion - - /** - * Returns the raw JSON value of [defaultModel]. - * - * Unlike [defaultModel], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("default_model") - @ExcludeMissing - fun _defaultModel(): JsonField = defaultModel - - /** - * Returns the raw JSON value of [llmBudgetTable]. - * - * Unlike [llmBudgetTable], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("llm_budget_table") - @ExcludeMissing - fun _llmBudgetTable(): JsonField = llmBudgetTable - - /** - * Returns the raw JSON value of [spend]. - * - * Unlike [spend], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("spend") @ExcludeMissing fun _spend(): JsonField = spend - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [CustomerRetrieveInfoResponse]. - * - * The following fields are required: - * ```java - * .blocked() - * .userId() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [CustomerRetrieveInfoResponse]. */ - class Builder internal constructor() { - - private var blocked: JsonField? = null - private var userId: JsonField? = null - private var alias: JsonField = JsonMissing.of() - private var allowedModelRegion: JsonField = JsonMissing.of() - private var defaultModel: JsonField = JsonMissing.of() - private var llmBudgetTable: JsonField = JsonMissing.of() - private var spend: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(customerRetrieveInfoResponse: CustomerRetrieveInfoResponse) = apply { - blocked = customerRetrieveInfoResponse.blocked - userId = customerRetrieveInfoResponse.userId - alias = customerRetrieveInfoResponse.alias - allowedModelRegion = customerRetrieveInfoResponse.allowedModelRegion - defaultModel = customerRetrieveInfoResponse.defaultModel - llmBudgetTable = customerRetrieveInfoResponse.llmBudgetTable - spend = customerRetrieveInfoResponse.spend - additionalProperties = customerRetrieveInfoResponse.additionalProperties.toMutableMap() - } - - fun blocked(blocked: Boolean) = blocked(JsonField.of(blocked)) - - /** - * Sets [Builder.blocked] to an arbitrary JSON value. - * - * You should usually call [Builder.blocked] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun blocked(blocked: JsonField) = apply { this.blocked = blocked } - - fun userId(userId: String) = userId(JsonField.of(userId)) - - /** - * Sets [Builder.userId] to an arbitrary JSON value. - * - * You should usually call [Builder.userId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun userId(userId: JsonField) = apply { this.userId = userId } - - fun alias(alias: String?) = alias(JsonField.ofNullable(alias)) - - /** Alias for calling [Builder.alias] with `alias.orElse(null)`. */ - fun alias(alias: Optional) = alias(alias.getOrNull()) - - /** - * Sets [Builder.alias] to an arbitrary JSON value. - * - * You should usually call [Builder.alias] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun alias(alias: JsonField) = apply { this.alias = alias } - - fun allowedModelRegion(allowedModelRegion: AllowedModelRegion?) = - allowedModelRegion(JsonField.ofNullable(allowedModelRegion)) - - /** - * Alias for calling [Builder.allowedModelRegion] with `allowedModelRegion.orElse(null)`. - */ - fun allowedModelRegion(allowedModelRegion: Optional) = - allowedModelRegion(allowedModelRegion.getOrNull()) - - /** - * Sets [Builder.allowedModelRegion] to an arbitrary JSON value. - * - * You should usually call [Builder.allowedModelRegion] with a well-typed - * [AllowedModelRegion] value instead. This method is primarily for setting the field to an - * undocumented or not yet supported value. - */ - fun allowedModelRegion(allowedModelRegion: JsonField) = apply { - this.allowedModelRegion = allowedModelRegion - } - - fun defaultModel(defaultModel: String?) = defaultModel(JsonField.ofNullable(defaultModel)) - - /** Alias for calling [Builder.defaultModel] with `defaultModel.orElse(null)`. */ - fun defaultModel(defaultModel: Optional) = defaultModel(defaultModel.getOrNull()) - - /** - * Sets [Builder.defaultModel] to an arbitrary JSON value. - * - * You should usually call [Builder.defaultModel] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun defaultModel(defaultModel: JsonField) = apply { - this.defaultModel = defaultModel - } - - /** Represents user-controllable params for a LLM_BudgetTable record */ - fun llmBudgetTable(llmBudgetTable: LlmBudgetTable?) = - llmBudgetTable(JsonField.ofNullable(llmBudgetTable)) - - /** Alias for calling [Builder.llmBudgetTable] with `llmBudgetTable.orElse(null)`. */ - fun llmBudgetTable(llmBudgetTable: Optional) = - llmBudgetTable(llmBudgetTable.getOrNull()) - - /** - * Sets [Builder.llmBudgetTable] to an arbitrary JSON value. - * - * You should usually call [Builder.llmBudgetTable] with a well-typed [LlmBudgetTable] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun llmBudgetTable(llmBudgetTable: JsonField) = apply { - this.llmBudgetTable = llmBudgetTable - } - - fun spend(spend: Double) = spend(JsonField.of(spend)) - - /** - * Sets [Builder.spend] to an arbitrary JSON value. - * - * You should usually call [Builder.spend] with a well-typed [Double] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun spend(spend: JsonField) = apply { this.spend = spend } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [CustomerRetrieveInfoResponse]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .blocked() - * .userId() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): CustomerRetrieveInfoResponse = - CustomerRetrieveInfoResponse( - checkRequired("blocked", blocked), - checkRequired("userId", userId), - alias, - allowedModelRegion, - defaultModel, - llmBudgetTable, - spend, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): CustomerRetrieveInfoResponse = apply { - if (validated) { - return@apply - } - - blocked() - userId() - alias() - allowedModelRegion() - defaultModel() - llmBudgetTable().ifPresent { it.validate() } - spend() - validated = true - } - - class AllowedModelRegion - @JsonCreator - private constructor(private val value: JsonField) : Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val EU = of("eu") - - @JvmField val US = of("us") - - @JvmStatic fun of(value: String) = AllowedModelRegion(JsonField.of(value)) - } - - /** An enum containing [AllowedModelRegion]'s known values. */ - enum class Known { - EU, - US, - } - - /** - * An enum containing [AllowedModelRegion]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [AllowedModelRegion] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - EU, - US, - /** - * An enum member indicating that [AllowedModelRegion] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - EU -> Value.EU - US -> Value.US - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws HanzoInvalidDataException if this class instance's value is a not a known member. - */ - fun known(): Known = - when (this) { - EU -> Known.EU - US -> Known.US - else -> throw HanzoInvalidDataException("Unknown AllowedModelRegion: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws HanzoInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AllowedModelRegion && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - /** Represents user-controllable params for a LLM_BudgetTable record */ - class LlmBudgetTable - private constructor( - private val budgetDuration: JsonField, - private val maxBudget: JsonField, - private val maxParallelRequests: JsonField, - private val modelMaxBudget: JsonValue, - private val rpmLimit: JsonField, - private val softBudget: JsonField, - private val tpmLimit: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("budget_duration") - @ExcludeMissing - budgetDuration: JsonField = JsonMissing.of(), - @JsonProperty("max_budget") - @ExcludeMissing - maxBudget: JsonField = JsonMissing.of(), - @JsonProperty("max_parallel_requests") - @ExcludeMissing - maxParallelRequests: JsonField = JsonMissing.of(), - @JsonProperty("model_max_budget") - @ExcludeMissing - modelMaxBudget: JsonValue = JsonMissing.of(), - @JsonProperty("rpm_limit") @ExcludeMissing rpmLimit: JsonField = JsonMissing.of(), - @JsonProperty("soft_budget") - @ExcludeMissing - softBudget: JsonField = JsonMissing.of(), - @JsonProperty("tpm_limit") @ExcludeMissing tpmLimit: JsonField = JsonMissing.of(), - ) : this( - budgetDuration, - maxBudget, - maxParallelRequests, - modelMaxBudget, - rpmLimit, - softBudget, - tpmLimit, - mutableMapOf(), - ) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun budgetDuration(): Optional = - Optional.ofNullable(budgetDuration.getNullable("budget_duration")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun maxBudget(): Optional = Optional.ofNullable(maxBudget.getNullable("max_budget")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun maxParallelRequests(): Optional = - Optional.ofNullable(maxParallelRequests.getNullable("max_parallel_requests")) - - @JsonProperty("model_max_budget") - @ExcludeMissing - fun _modelMaxBudget(): JsonValue = modelMaxBudget - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun rpmLimit(): Optional = Optional.ofNullable(rpmLimit.getNullable("rpm_limit")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun softBudget(): Optional = - Optional.ofNullable(softBudget.getNullable("soft_budget")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun tpmLimit(): Optional = Optional.ofNullable(tpmLimit.getNullable("tpm_limit")) - - /** - * Returns the raw JSON value of [budgetDuration]. - * - * Unlike [budgetDuration], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("budget_duration") - @ExcludeMissing - fun _budgetDuration(): JsonField = budgetDuration - - /** - * Returns the raw JSON value of [maxBudget]. - * - * Unlike [maxBudget], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("max_budget") @ExcludeMissing fun _maxBudget(): JsonField = maxBudget - - /** - * Returns the raw JSON value of [maxParallelRequests]. - * - * Unlike [maxParallelRequests], this method doesn't throw if the JSON field has an - * unexpected type. - */ - @JsonProperty("max_parallel_requests") - @ExcludeMissing - fun _maxParallelRequests(): JsonField = maxParallelRequests - - /** - * Returns the raw JSON value of [rpmLimit]. - * - * Unlike [rpmLimit], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("rpm_limit") @ExcludeMissing fun _rpmLimit(): JsonField = rpmLimit - - /** - * Returns the raw JSON value of [softBudget]. - * - * Unlike [softBudget], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("soft_budget") - @ExcludeMissing - fun _softBudget(): JsonField = softBudget - - /** - * Returns the raw JSON value of [tpmLimit]. - * - * Unlike [tpmLimit], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("tpm_limit") @ExcludeMissing fun _tpmLimit(): JsonField = tpmLimit - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [LlmBudgetTable]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [LlmBudgetTable]. */ - class Builder internal constructor() { - - private var budgetDuration: JsonField = JsonMissing.of() - private var maxBudget: JsonField = JsonMissing.of() - private var maxParallelRequests: JsonField = JsonMissing.of() - private var modelMaxBudget: JsonValue = JsonMissing.of() - private var rpmLimit: JsonField = JsonMissing.of() - private var softBudget: JsonField = JsonMissing.of() - private var tpmLimit: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(llmBudgetTable: LlmBudgetTable) = apply { - budgetDuration = llmBudgetTable.budgetDuration - maxBudget = llmBudgetTable.maxBudget - maxParallelRequests = llmBudgetTable.maxParallelRequests - modelMaxBudget = llmBudgetTable.modelMaxBudget - rpmLimit = llmBudgetTable.rpmLimit - softBudget = llmBudgetTable.softBudget - tpmLimit = llmBudgetTable.tpmLimit - additionalProperties = llmBudgetTable.additionalProperties.toMutableMap() - } - - fun budgetDuration(budgetDuration: String?) = - budgetDuration(JsonField.ofNullable(budgetDuration)) - - /** Alias for calling [Builder.budgetDuration] with `budgetDuration.orElse(null)`. */ - fun budgetDuration(budgetDuration: Optional) = - budgetDuration(budgetDuration.getOrNull()) - - /** - * Sets [Builder.budgetDuration] to an arbitrary JSON value. - * - * You should usually call [Builder.budgetDuration] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun budgetDuration(budgetDuration: JsonField) = apply { - this.budgetDuration = budgetDuration - } - - fun maxBudget(maxBudget: Double?) = maxBudget(JsonField.ofNullable(maxBudget)) - - /** - * Alias for [Builder.maxBudget]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun maxBudget(maxBudget: Double) = maxBudget(maxBudget as Double?) - - /** Alias for calling [Builder.maxBudget] with `maxBudget.orElse(null)`. */ - fun maxBudget(maxBudget: Optional) = maxBudget(maxBudget.getOrNull()) - - /** - * Sets [Builder.maxBudget] to an arbitrary JSON value. - * - * You should usually call [Builder.maxBudget] with a well-typed [Double] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxBudget(maxBudget: JsonField) = apply { this.maxBudget = maxBudget } - - fun maxParallelRequests(maxParallelRequests: Long?) = - maxParallelRequests(JsonField.ofNullable(maxParallelRequests)) - - /** - * Alias for [Builder.maxParallelRequests]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun maxParallelRequests(maxParallelRequests: Long) = - maxParallelRequests(maxParallelRequests as Long?) - - /** - * Alias for calling [Builder.maxParallelRequests] with - * `maxParallelRequests.orElse(null)`. - */ - fun maxParallelRequests(maxParallelRequests: Optional) = - maxParallelRequests(maxParallelRequests.getOrNull()) - - /** - * Sets [Builder.maxParallelRequests] to an arbitrary JSON value. - * - * You should usually call [Builder.maxParallelRequests] with a well-typed [Long] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxParallelRequests(maxParallelRequests: JsonField) = apply { - this.maxParallelRequests = maxParallelRequests - } - - fun modelMaxBudget(modelMaxBudget: JsonValue) = apply { - this.modelMaxBudget = modelMaxBudget - } - - fun rpmLimit(rpmLimit: Long?) = rpmLimit(JsonField.ofNullable(rpmLimit)) - - /** - * Alias for [Builder.rpmLimit]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun rpmLimit(rpmLimit: Long) = rpmLimit(rpmLimit as Long?) - - /** Alias for calling [Builder.rpmLimit] with `rpmLimit.orElse(null)`. */ - fun rpmLimit(rpmLimit: Optional) = rpmLimit(rpmLimit.getOrNull()) - - /** - * Sets [Builder.rpmLimit] to an arbitrary JSON value. - * - * You should usually call [Builder.rpmLimit] with a well-typed [Long] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun rpmLimit(rpmLimit: JsonField) = apply { this.rpmLimit = rpmLimit } - - fun softBudget(softBudget: Double?) = softBudget(JsonField.ofNullable(softBudget)) - - /** - * Alias for [Builder.softBudget]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun softBudget(softBudget: Double) = softBudget(softBudget as Double?) - - /** Alias for calling [Builder.softBudget] with `softBudget.orElse(null)`. */ - fun softBudget(softBudget: Optional) = softBudget(softBudget.getOrNull()) - - /** - * Sets [Builder.softBudget] to an arbitrary JSON value. - * - * You should usually call [Builder.softBudget] with a well-typed [Double] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun softBudget(softBudget: JsonField) = apply { this.softBudget = softBudget } - - fun tpmLimit(tpmLimit: Long?) = tpmLimit(JsonField.ofNullable(tpmLimit)) - - /** - * Alias for [Builder.tpmLimit]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun tpmLimit(tpmLimit: Long) = tpmLimit(tpmLimit as Long?) - - /** Alias for calling [Builder.tpmLimit] with `tpmLimit.orElse(null)`. */ - fun tpmLimit(tpmLimit: Optional) = tpmLimit(tpmLimit.getOrNull()) - - /** - * Sets [Builder.tpmLimit] to an arbitrary JSON value. - * - * You should usually call [Builder.tpmLimit] with a well-typed [Long] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun tpmLimit(tpmLimit: JsonField) = apply { this.tpmLimit = tpmLimit } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [LlmBudgetTable]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): LlmBudgetTable = - LlmBudgetTable( - budgetDuration, - maxBudget, - maxParallelRequests, - modelMaxBudget, - rpmLimit, - softBudget, - tpmLimit, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): LlmBudgetTable = apply { - if (validated) { - return@apply - } - - budgetDuration() - maxBudget() - maxParallelRequests() - rpmLimit() - softBudget() - tpmLimit() - validated = true - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is LlmBudgetTable && budgetDuration == other.budgetDuration && maxBudget == other.maxBudget && maxParallelRequests == other.maxParallelRequests && modelMaxBudget == other.modelMaxBudget && rpmLimit == other.rpmLimit && softBudget == other.softBudget && tpmLimit == other.tpmLimit && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(budgetDuration, maxBudget, maxParallelRequests, modelMaxBudget, rpmLimit, softBudget, tpmLimit, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "LlmBudgetTable{budgetDuration=$budgetDuration, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, modelMaxBudget=$modelMaxBudget, rpmLimit=$rpmLimit, softBudget=$softBudget, tpmLimit=$tpmLimit, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is CustomerRetrieveInfoResponse && blocked == other.blocked && userId == other.userId && alias == other.alias && allowedModelRegion == other.allowedModelRegion && defaultModel == other.defaultModel && llmBudgetTable == other.llmBudgetTable && spend == other.spend && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(blocked, userId, alias, allowedModelRegion, defaultModel, llmBudgetTable, spend, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "CustomerRetrieveInfoResponse{blocked=$blocked, userId=$userId, alias=$alias, allowedModelRegion=$allowedModelRegion, defaultModel=$defaultModel, llmBudgetTable=$llmBudgetTable, spend=$spend, additionalProperties=$additionalProperties}" -} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUnblockParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUnblockParams.kt index 20b7efc7..62afee21 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUnblockParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUnblockParams.kt @@ -33,8 +33,10 @@ private constructor( fun _additionalBodyProperties(): Map = blockUsers._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -186,7 +188,7 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): BlockUsers = blockUsers + fun _body(): BlockUsers = blockUsers override fun _headers(): Headers = additionalHeaders @@ -197,10 +199,14 @@ private constructor( return true } - return /* spotless:off */ other is CustomerUnblockParams && blockUsers == other.blockUsers && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is CustomerUnblockParams && + blockUsers == other.blockUsers && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(blockUsers, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(blockUsers, additionalHeaders, additionalQueryParams) override fun toString() = "CustomerUnblockParams{blockUsers=$blockUsers, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUnblockResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUnblockResponse.kt index 11cd2864..667b720a 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUnblockResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUnblockResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.customer import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CustomerUnblockResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap = body._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -179,6 +181,20 @@ private constructor( additionalQueryParams = customerUpdateParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [userId] + * - [alias] + * - [allowedModelRegion] + * - [blocked] + * - [budgetId] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun userId(userId: String) = apply { body.userId(userId) } /** @@ -420,7 +436,7 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): Body = body + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders @@ -428,6 +444,7 @@ private constructor( /** Update a Customer, use this to update customer budgets etc */ class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val userId: JsonField, private val alias: JsonField, @@ -477,39 +494,38 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun alias(): Optional = Optional.ofNullable(alias.getNullable("alias")) + fun alias(): Optional = alias.getOptional("alias") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun allowedModelRegion(): Optional = - Optional.ofNullable(allowedModelRegion.getNullable("allowed_model_region")) + allowedModelRegion.getOptional("allowed_model_region") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun blocked(): Optional = Optional.ofNullable(blocked.getNullable("blocked")) + fun blocked(): Optional = blocked.getOptional("blocked") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetId(): Optional = Optional.ofNullable(budgetId.getNullable("budget_id")) + fun budgetId(): Optional = budgetId.getOptional("budget_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun defaultModel(): Optional = - Optional.ofNullable(defaultModel.getNullable("default_model")) + fun defaultModel(): Optional = defaultModel.getOptional("default_model") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun maxBudget(): Optional = Optional.ofNullable(maxBudget.getNullable("max_budget")) + fun maxBudget(): Optional = maxBudget.getOptional("max_budget") /** * Returns the raw JSON value of [userId]. @@ -778,7 +794,7 @@ private constructor( userId() alias() - allowedModelRegion() + allowedModelRegion().ifPresent { it.validate() } blocked() budgetId() defaultModel() @@ -786,18 +802,59 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (userId.asKnown().isPresent) 1 else 0) + + (if (alias.asKnown().isPresent) 1 else 0) + + (allowedModelRegion.asKnown().getOrNull()?.validity() ?: 0) + + (if (blocked.asKnown().isPresent) 1 else 0) + + (if (budgetId.asKnown().isPresent) 1 else 0) + + (if (defaultModel.asKnown().isPresent) 1 else 0) + + (if (maxBudget.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && userId == other.userId && alias == other.alias && allowedModelRegion == other.allowedModelRegion && blocked == other.blocked && budgetId == other.budgetId && defaultModel == other.defaultModel && maxBudget == other.maxBudget && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Body && + userId == other.userId && + alias == other.alias && + allowedModelRegion == other.allowedModelRegion && + blocked == other.blocked && + budgetId == other.budgetId && + defaultModel == other.defaultModel && + maxBudget == other.maxBudget && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + userId, + alias, + allowedModelRegion, + blocked, + budgetId, + defaultModel, + maxBudget, + additionalProperties, + ) } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(userId, alias, allowedModelRegion, blocked, budgetId, defaultModel, maxBudget, additionalProperties) } - /* spotless:on */ - override fun hashCode(): Int = hashCode override fun toString() = @@ -893,12 +950,39 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AllowedModelRegion = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is AllowedModelRegion && value == other.value /* spotless:on */ + return other is AllowedModelRegion && value == other.value } override fun hashCode() = value.hashCode() @@ -911,10 +995,13 @@ private constructor( return true } - return /* spotless:off */ other is CustomerUpdateParams && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is CustomerUpdateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) override fun toString() = "CustomerUpdateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUpdateResponse.kt index eb0313db..5c14d9b5 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/customer/CustomerUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.customer import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CustomerUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, + private val userId: JsonField, + private val alias: JsonField, + private val allowedModelRegion: JsonField, + private val defaultModel: JsonField, + private val litellmBudgetTable: JsonField, + private val spend: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("blocked") @ExcludeMissing blocked: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + @JsonProperty("alias") @ExcludeMissing alias: JsonField = JsonMissing.of(), + @JsonProperty("allowed_model_region") + @ExcludeMissing + allowedModelRegion: JsonField = JsonMissing.of(), + @JsonProperty("default_model") + @ExcludeMissing + defaultModel: JsonField = JsonMissing.of(), + @JsonProperty("litellm_budget_table") + @ExcludeMissing + litellmBudgetTable: JsonField = JsonMissing.of(), + @JsonProperty("spend") @ExcludeMissing spend: JsonField = JsonMissing.of(), + ) : this( + blocked, + userId, + alias, + allowedModelRegion, + defaultModel, + litellmBudgetTable, + spend, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun blocked(): Boolean = blocked.getRequired("blocked") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun userId(): String = userId.getRequired("user_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun alias(): Optional = alias.getOptional("alias") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedModelRegion(): Optional = + allowedModelRegion.getOptional("allowed_model_region") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun defaultModel(): Optional = defaultModel.getOptional("default_model") + + /** + * Represents user-controllable params for a LiteLLM_BudgetTable record + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmBudgetTable(): Optional = + litellmBudgetTable.getOptional("litellm_budget_table") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spend(): Optional = spend.getOptional("spend") + + /** + * Returns the raw JSON value of [blocked]. + * + * Unlike [blocked], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("blocked") @ExcludeMissing fun _blocked(): JsonField = blocked + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + /** + * Returns the raw JSON value of [alias]. + * + * Unlike [alias], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("alias") @ExcludeMissing fun _alias(): JsonField = alias + + /** + * Returns the raw JSON value of [allowedModelRegion]. + * + * Unlike [allowedModelRegion], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("allowed_model_region") + @ExcludeMissing + fun _allowedModelRegion(): JsonField = allowedModelRegion + + /** + * Returns the raw JSON value of [defaultModel]. + * + * Unlike [defaultModel], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("default_model") + @ExcludeMissing + fun _defaultModel(): JsonField = defaultModel + + /** + * Returns the raw JSON value of [litellmBudgetTable]. + * + * Unlike [litellmBudgetTable], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("litellm_budget_table") + @ExcludeMissing + fun _litellmBudgetTable(): JsonField = litellmBudgetTable + + /** + * Returns the raw JSON value of [spend]. + * + * Unlike [spend], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("spend") @ExcludeMissing fun _spend(): JsonField = spend + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [LiteLlmEndUserTable]. + * + * The following fields are required: + * ```java + * .blocked() + * .userId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LiteLlmEndUserTable]. */ + class Builder internal constructor() { + + private var blocked: JsonField? = null + private var userId: JsonField? = null + private var alias: JsonField = JsonMissing.of() + private var allowedModelRegion: JsonField = JsonMissing.of() + private var defaultModel: JsonField = JsonMissing.of() + private var litellmBudgetTable: JsonField = JsonMissing.of() + private var spend: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(liteLlmEndUserTable: LiteLlmEndUserTable) = apply { + blocked = liteLlmEndUserTable.blocked + userId = liteLlmEndUserTable.userId + alias = liteLlmEndUserTable.alias + allowedModelRegion = liteLlmEndUserTable.allowedModelRegion + defaultModel = liteLlmEndUserTable.defaultModel + litellmBudgetTable = liteLlmEndUserTable.litellmBudgetTable + spend = liteLlmEndUserTable.spend + additionalProperties = liteLlmEndUserTable.additionalProperties.toMutableMap() + } + + fun blocked(blocked: Boolean) = blocked(JsonField.of(blocked)) + + /** + * Sets [Builder.blocked] to an arbitrary JSON value. + * + * You should usually call [Builder.blocked] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun blocked(blocked: JsonField) = apply { this.blocked = blocked } + + fun userId(userId: String) = userId(JsonField.of(userId)) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun alias(alias: String?) = alias(JsonField.ofNullable(alias)) + + /** Alias for calling [Builder.alias] with `alias.orElse(null)`. */ + fun alias(alias: Optional) = alias(alias.getOrNull()) + + /** + * Sets [Builder.alias] to an arbitrary JSON value. + * + * You should usually call [Builder.alias] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun alias(alias: JsonField) = apply { this.alias = alias } + + fun allowedModelRegion(allowedModelRegion: AllowedModelRegion?) = + allowedModelRegion(JsonField.ofNullable(allowedModelRegion)) + + /** + * Alias for calling [Builder.allowedModelRegion] with `allowedModelRegion.orElse(null)`. + */ + fun allowedModelRegion(allowedModelRegion: Optional) = + allowedModelRegion(allowedModelRegion.getOrNull()) + + /** + * Sets [Builder.allowedModelRegion] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedModelRegion] with a well-typed + * [AllowedModelRegion] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun allowedModelRegion(allowedModelRegion: JsonField) = apply { + this.allowedModelRegion = allowedModelRegion + } + + fun defaultModel(defaultModel: String?) = defaultModel(JsonField.ofNullable(defaultModel)) + + /** Alias for calling [Builder.defaultModel] with `defaultModel.orElse(null)`. */ + fun defaultModel(defaultModel: Optional) = defaultModel(defaultModel.getOrNull()) + + /** + * Sets [Builder.defaultModel] to an arbitrary JSON value. + * + * You should usually call [Builder.defaultModel] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun defaultModel(defaultModel: JsonField) = apply { + this.defaultModel = defaultModel + } + + /** Represents user-controllable params for a LiteLLM_BudgetTable record */ + fun litellmBudgetTable(litellmBudgetTable: BudgetTable?) = + litellmBudgetTable(JsonField.ofNullable(litellmBudgetTable)) + + /** + * Alias for calling [Builder.litellmBudgetTable] with `litellmBudgetTable.orElse(null)`. + */ + fun litellmBudgetTable(litellmBudgetTable: Optional) = + litellmBudgetTable(litellmBudgetTable.getOrNull()) + + /** + * Sets [Builder.litellmBudgetTable] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmBudgetTable] with a well-typed [BudgetTable] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun litellmBudgetTable(litellmBudgetTable: JsonField) = apply { + this.litellmBudgetTable = litellmBudgetTable + } + + fun spend(spend: Double) = spend(JsonField.of(spend)) + + /** + * Sets [Builder.spend] to an arbitrary JSON value. + * + * You should usually call [Builder.spend] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun spend(spend: JsonField) = apply { this.spend = spend } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [LiteLlmEndUserTable]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .blocked() + * .userId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): LiteLlmEndUserTable = + LiteLlmEndUserTable( + checkRequired("blocked", blocked), + checkRequired("userId", userId), + alias, + allowedModelRegion, + defaultModel, + litellmBudgetTable, + spend, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): LiteLlmEndUserTable = apply { + if (validated) { + return@apply + } + + blocked() + userId() + alias() + allowedModelRegion().ifPresent { it.validate() } + defaultModel() + litellmBudgetTable().ifPresent { it.validate() } + spend() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (blocked.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + (if (alias.asKnown().isPresent) 1 else 0) + + (allowedModelRegion.asKnown().getOrNull()?.validity() ?: 0) + + (if (defaultModel.asKnown().isPresent) 1 else 0) + + (litellmBudgetTable.asKnown().getOrNull()?.validity() ?: 0) + + (if (spend.asKnown().isPresent) 1 else 0) + + class AllowedModelRegion + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EU = of("eu") + + @JvmField val US = of("us") + + @JvmStatic fun of(value: String) = AllowedModelRegion(JsonField.of(value)) + } + + /** An enum containing [AllowedModelRegion]'s known values. */ + enum class Known { + EU, + US, + } + + /** + * An enum containing [AllowedModelRegion]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [AllowedModelRegion] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + EU, + US, + /** + * An enum member indicating that [AllowedModelRegion] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + EU -> Value.EU + US -> Value.US + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + EU -> Known.EU + US -> Known.US + else -> throw HanzoInvalidDataException("Unknown AllowedModelRegion: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): AllowedModelRegion = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AllowedModelRegion && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is LiteLlmEndUserTable && + blocked == other.blocked && + userId == other.userId && + alias == other.alias && + allowedModelRegion == other.allowedModelRegion && + defaultModel == other.defaultModel && + litellmBudgetTable == other.litellmBudgetTable && + spend == other.spend && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + blocked, + userId, + alias, + allowedModelRegion, + defaultModel, + litellmBudgetTable, + spend, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "LiteLlmEndUserTable{blocked=$blocked, userId=$userId, alias=$alias, allowedModelRegion=$allowedModelRegion, defaultModel=$defaultModel, litellmBudgetTable=$litellmBudgetTable, spend=$spend, additionalProperties=$additionalProperties}" +} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/delete/DeleteCreateAllowedIpParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/delete/DeleteCreateAllowedIpParams.kt index cb74bec4..18322c25 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/delete/DeleteCreateAllowedIpParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/delete/DeleteCreateAllowedIpParams.kt @@ -22,8 +22,10 @@ private constructor( fun _additionalBodyProperties(): Map = ipAddress._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -175,7 +177,7 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): IpAddress = ipAddress + fun _body(): IpAddress = ipAddress override fun _headers(): Headers = additionalHeaders @@ -186,10 +188,13 @@ private constructor( return true } - return /* spotless:off */ other is DeleteCreateAllowedIpParams && ipAddress == other.ipAddress && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is DeleteCreateAllowedIpParams && + ipAddress == other.ipAddress && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(ipAddress, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(ipAddress, additionalHeaders, additionalQueryParams) override fun toString() = "DeleteCreateAllowedIpParams{ipAddress=$ipAddress, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/delete/DeleteCreateAllowedIpResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/delete/DeleteCreateAllowedIpResponse.kt index b76b711f..529987de 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/delete/DeleteCreateAllowedIpResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/delete/DeleteCreateAllowedIpResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.delete import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class DeleteCreateAllowedIpResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -84,17 +86,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun model(): Optional = Optional.ofNullable(model) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun model(): String = body.model() - fun _additionalBodyProperties(): Map = additionalBodyProperties + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiBase(): Optional = body.apiBase() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiKey(): Optional = body.apiKey() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiType(): Optional = body.apiType() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiVersion(): Optional = body.apiVersion() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun caching(): Optional = body.caching() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customLlmProvider(): Optional = body.customLlmProvider() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun input(): Optional> = body.input() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmCallId(): Optional = body.litellmCallId() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmLoggingObj(): Optional = body.litellmLoggingObj() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun loggerFn(): Optional = body.loggerFn() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = body.timeout() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun user(): Optional = body.user() + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _model(): JsonField = body._model() + + /** + * Returns the raw JSON value of [apiBase]. + * + * Unlike [apiBase], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _apiBase(): JsonField = body._apiBase() + + /** + * Returns the raw JSON value of [apiKey]. + * + * Unlike [apiKey], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _apiKey(): JsonField = body._apiKey() + + /** + * Returns the raw JSON value of [apiType]. + * + * Unlike [apiType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _apiType(): JsonField = body._apiType() + + /** + * Returns the raw JSON value of [apiVersion]. + * + * Unlike [apiVersion], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _apiVersion(): JsonField = body._apiVersion() + + /** + * Returns the raw JSON value of [caching]. + * + * Unlike [caching], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _caching(): JsonField = body._caching() + + /** + * Returns the raw JSON value of [customLlmProvider]. + * + * Unlike [customLlmProvider], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _customLlmProvider(): JsonField = body._customLlmProvider() + + /** + * Returns the raw JSON value of [input]. + * + * Unlike [input], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _input(): JsonField> = body._input() + + /** + * Returns the raw JSON value of [litellmCallId]. + * + * Unlike [litellmCallId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _litellmCallId(): JsonField = body._litellmCallId() + + /** + * Returns the raw JSON value of [litellmLoggingObj]. + * + * Unlike [litellmLoggingObj], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _litellmLoggingObj(): JsonField = body._litellmLoggingObj() + + /** + * Returns the raw JSON value of [loggerFn]. + * + * Unlike [loggerFn], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _loggerFn(): JsonField = body._loggerFn() + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _timeout(): JsonField = body._timeout() + + /** + * Returns the raw JSON value of [user]. + * + * Unlike [user], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _user(): JsonField = body._user() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - @JvmStatic fun none(): EmbeddingCreateParams = builder().build() - - /** Returns a mutable builder for constructing an instance of [EmbeddingCreateParams]. */ + /** + * Returns a mutable builder for constructing an instance of [EmbeddingCreateParams]. + * + * The following fields are required: + * ```java + * .model() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [EmbeddingCreateParams]. */ class Builder internal constructor() { - private var model: String? = null + private var body: Body.Builder = Body.builder() private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(embeddingCreateParams: EmbeddingCreateParams) = apply { - model = embeddingCreateParams.model + body = embeddingCreateParams.body.toBuilder() additionalHeaders = embeddingCreateParams.additionalHeaders.toBuilder() additionalQueryParams = embeddingCreateParams.additionalQueryParams.toBuilder() - additionalBodyProperties = embeddingCreateParams.additionalBodyProperties.toMutableMap() } - fun model(model: String?) = apply { this.model = model } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [model] + * - [apiBase] + * - [apiKey] + * - [apiType] + * - [apiVersion] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + fun model(model: String) = apply { body.model(model) } + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun model(model: JsonField) = apply { body.model(model) } + + fun apiBase(apiBase: String?) = apply { body.apiBase(apiBase) } + + /** Alias for calling [Builder.apiBase] with `apiBase.orElse(null)`. */ + fun apiBase(apiBase: Optional) = apiBase(apiBase.getOrNull()) + + /** + * Sets [Builder.apiBase] to an arbitrary JSON value. + * + * You should usually call [Builder.apiBase] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun apiBase(apiBase: JsonField) = apply { body.apiBase(apiBase) } + + fun apiKey(apiKey: String?) = apply { body.apiKey(apiKey) } + + /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ + fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) + + /** + * Sets [Builder.apiKey] to an arbitrary JSON value. + * + * You should usually call [Builder.apiKey] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun apiKey(apiKey: JsonField) = apply { body.apiKey(apiKey) } + + fun apiType(apiType: String?) = apply { body.apiType(apiType) } + + /** Alias for calling [Builder.apiType] with `apiType.orElse(null)`. */ + fun apiType(apiType: Optional) = apiType(apiType.getOrNull()) + + /** + * Sets [Builder.apiType] to an arbitrary JSON value. + * + * You should usually call [Builder.apiType] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun apiType(apiType: JsonField) = apply { body.apiType(apiType) } + + fun apiVersion(apiVersion: String?) = apply { body.apiVersion(apiVersion) } + + /** Alias for calling [Builder.apiVersion] with `apiVersion.orElse(null)`. */ + fun apiVersion(apiVersion: Optional) = apiVersion(apiVersion.getOrNull()) - /** Alias for calling [Builder.model] with `model.orElse(null)`. */ - fun model(model: Optional) = model(model.getOrNull()) + /** + * Sets [Builder.apiVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.apiVersion] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun apiVersion(apiVersion: JsonField) = apply { body.apiVersion(apiVersion) } + + fun caching(caching: Boolean) = apply { body.caching(caching) } + + /** + * Sets [Builder.caching] to an arbitrary JSON value. + * + * You should usually call [Builder.caching] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun caching(caching: JsonField) = apply { body.caching(caching) } + + fun customLlmProvider(customLlmProvider: CustomLlmProvider?) = apply { + body.customLlmProvider(customLlmProvider) + } + + /** Alias for calling [Builder.customLlmProvider] with `customLlmProvider.orElse(null)`. */ + fun customLlmProvider(customLlmProvider: Optional) = + customLlmProvider(customLlmProvider.getOrNull()) + + /** + * Sets [Builder.customLlmProvider] to an arbitrary JSON value. + * + * You should usually call [Builder.customLlmProvider] with a well-typed [CustomLlmProvider] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun customLlmProvider(customLlmProvider: JsonField) = apply { + body.customLlmProvider(customLlmProvider) + } + + /** Alias for calling [customLlmProvider] with `CustomLlmProvider.ofString(string)`. */ + fun customLlmProvider(string: String) = apply { body.customLlmProvider(string) } + + /** + * Alias for calling [customLlmProvider] with + * `CustomLlmProvider.ofUnionMember1(unionMember1)`. + */ + fun customLlmProvider(unionMember1: CustomLlmProvider.UnionMember1) = apply { + body.customLlmProvider(unionMember1) + } + + fun input(input: List) = apply { body.input(input) } + + /** + * Sets [Builder.input] to an arbitrary JSON value. + * + * You should usually call [Builder.input] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun input(input: JsonField>) = apply { body.input(input) } + + /** + * Adds a single [String] to [Builder.input]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addInput(input: String) = apply { body.addInput(input) } + + fun litellmCallId(litellmCallId: String?) = apply { body.litellmCallId(litellmCallId) } + + /** Alias for calling [Builder.litellmCallId] with `litellmCallId.orElse(null)`. */ + fun litellmCallId(litellmCallId: Optional) = + litellmCallId(litellmCallId.getOrNull()) + + /** + * Sets [Builder.litellmCallId] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmCallId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun litellmCallId(litellmCallId: JsonField) = apply { + body.litellmCallId(litellmCallId) + } + + fun litellmLoggingObj(litellmLoggingObj: LitellmLoggingObj?) = apply { + body.litellmLoggingObj(litellmLoggingObj) + } + + /** Alias for calling [Builder.litellmLoggingObj] with `litellmLoggingObj.orElse(null)`. */ + fun litellmLoggingObj(litellmLoggingObj: Optional) = + litellmLoggingObj(litellmLoggingObj.getOrNull()) + + /** + * Sets [Builder.litellmLoggingObj] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmLoggingObj] with a well-typed [LitellmLoggingObj] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun litellmLoggingObj(litellmLoggingObj: JsonField) = apply { + body.litellmLoggingObj(litellmLoggingObj) + } + + fun loggerFn(loggerFn: String?) = apply { body.loggerFn(loggerFn) } + + /** Alias for calling [Builder.loggerFn] with `loggerFn.orElse(null)`. */ + fun loggerFn(loggerFn: Optional) = loggerFn(loggerFn.getOrNull()) + + /** + * Sets [Builder.loggerFn] to an arbitrary JSON value. + * + * You should usually call [Builder.loggerFn] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun loggerFn(loggerFn: JsonField) = apply { body.loggerFn(loggerFn) } + + fun timeout(timeout: Long) = apply { body.timeout(timeout) } + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun timeout(timeout: JsonField) = apply { body.timeout(timeout) } + + fun user(user: String?) = apply { body.user(user) } + + /** Alias for calling [Builder.user] with `user.orElse(null)`. */ + fun user(user: Optional) = user(user.getOrNull()) + + /** + * Sets [Builder.user] to an arbitrary JSON value. + * + * You should usually call [Builder.user] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun user(user: JsonField) = apply { body.user(user) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -170,66 +586,1091 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - putAllAdditionalBodyProperties(additionalBodyProperties) + /** + * Returns an immutable instance of [EmbeddingCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .model() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): EmbeddingCreateParams = + EmbeddingCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val model: JsonField, + private val apiBase: JsonField, + private val apiKey: JsonField, + private val apiType: JsonField, + private val apiVersion: JsonField, + private val caching: JsonField, + private val customLlmProvider: JsonField, + private val input: JsonField>, + private val litellmCallId: JsonField, + private val litellmLoggingObj: JsonField, + private val loggerFn: JsonField, + private val timeout: JsonField, + private val user: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of(), + @JsonProperty("api_base") @ExcludeMissing apiBase: JsonField = JsonMissing.of(), + @JsonProperty("api_key") @ExcludeMissing apiKey: JsonField = JsonMissing.of(), + @JsonProperty("api_type") @ExcludeMissing apiType: JsonField = JsonMissing.of(), + @JsonProperty("api_version") + @ExcludeMissing + apiVersion: JsonField = JsonMissing.of(), + @JsonProperty("caching") @ExcludeMissing caching: JsonField = JsonMissing.of(), + @JsonProperty("custom_llm_provider") + @ExcludeMissing + customLlmProvider: JsonField = JsonMissing.of(), + @JsonProperty("input") + @ExcludeMissing + input: JsonField> = JsonMissing.of(), + @JsonProperty("litellm_call_id") + @ExcludeMissing + litellmCallId: JsonField = JsonMissing.of(), + @JsonProperty("litellm_logging_obj") + @ExcludeMissing + litellmLoggingObj: JsonField = JsonMissing.of(), + @JsonProperty("logger_fn") + @ExcludeMissing + loggerFn: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + @JsonProperty("user") @ExcludeMissing user: JsonField = JsonMissing.of(), + ) : this( + model, + apiBase, + apiKey, + apiType, + apiVersion, + caching, + customLlmProvider, + input, + litellmCallId, + litellmLoggingObj, + loggerFn, + timeout, + user, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun model(): String = model.getRequired("model") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiBase(): Optional = apiBase.getOptional("api_base") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiKey(): Optional = apiKey.getOptional("api_key") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiType(): Optional = apiType.getOptional("api_type") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiVersion(): Optional = apiVersion.getOptional("api_version") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun caching(): Optional = caching.getOptional("caching") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customLlmProvider(): Optional = + customLlmProvider.getOptional("custom_llm_provider") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun input(): Optional> = input.getOptional("input") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmCallId(): Optional = litellmCallId.getOptional("litellm_call_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmLoggingObj(): Optional = + litellmLoggingObj.getOptional("litellm_logging_obj") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun loggerFn(): Optional = loggerFn.getOptional("logger_fn") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = timeout.getOptional("timeout") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun user(): Optional = user.getOptional("user") + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + /** + * Returns the raw JSON value of [apiBase]. + * + * Unlike [apiBase], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_base") @ExcludeMissing fun _apiBase(): JsonField = apiBase + + /** + * Returns the raw JSON value of [apiKey]. + * + * Unlike [apiKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_key") @ExcludeMissing fun _apiKey(): JsonField = apiKey + + /** + * Returns the raw JSON value of [apiType]. + * + * Unlike [apiType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_type") @ExcludeMissing fun _apiType(): JsonField = apiType + + /** + * Returns the raw JSON value of [apiVersion]. + * + * Unlike [apiVersion], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_version") + @ExcludeMissing + fun _apiVersion(): JsonField = apiVersion + + /** + * Returns the raw JSON value of [caching]. + * + * Unlike [caching], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("caching") @ExcludeMissing fun _caching(): JsonField = caching + + /** + * Returns the raw JSON value of [customLlmProvider]. + * + * Unlike [customLlmProvider], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("custom_llm_provider") + @ExcludeMissing + fun _customLlmProvider(): JsonField = customLlmProvider + + /** + * Returns the raw JSON value of [input]. + * + * Unlike [input], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonField> = input + + /** + * Returns the raw JSON value of [litellmCallId]. + * + * Unlike [litellmCallId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("litellm_call_id") + @ExcludeMissing + fun _litellmCallId(): JsonField = litellmCallId + + /** + * Returns the raw JSON value of [litellmLoggingObj]. + * + * Unlike [litellmLoggingObj], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("litellm_logging_obj") + @ExcludeMissing + fun _litellmLoggingObj(): JsonField = litellmLoggingObj + + /** + * Returns the raw JSON value of [loggerFn]. + * + * Unlike [loggerFn], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("logger_fn") @ExcludeMissing fun _loggerFn(): JsonField = loggerFn + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + /** + * Returns the raw JSON value of [user]. + * + * Unlike [user], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user") @ExcludeMissing fun _user(): JsonField = user + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - additionalBodyProperties.put(key, value) + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .model() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var model: JsonField? = null + private var apiBase: JsonField = JsonMissing.of() + private var apiKey: JsonField = JsonMissing.of() + private var apiType: JsonField = JsonMissing.of() + private var apiVersion: JsonField = JsonMissing.of() + private var caching: JsonField = JsonMissing.of() + private var customLlmProvider: JsonField = JsonMissing.of() + private var input: JsonField>? = null + private var litellmCallId: JsonField = JsonMissing.of() + private var litellmLoggingObj: JsonField = JsonMissing.of() + private var loggerFn: JsonField = JsonMissing.of() + private var timeout: JsonField = JsonMissing.of() + private var user: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + model = body.model + apiBase = body.apiBase + apiKey = body.apiKey + apiType = body.apiType + apiVersion = body.apiVersion + caching = body.caching + customLlmProvider = body.customLlmProvider + input = body.input.map { it.toMutableList() } + litellmCallId = body.litellmCallId + litellmLoggingObj = body.litellmLoggingObj + loggerFn = body.loggerFn + timeout = body.timeout + user = body.user + additionalProperties = body.additionalProperties.toMutableMap() + } + + fun model(model: String) = model(JsonField.of(model)) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun apiBase(apiBase: String?) = apiBase(JsonField.ofNullable(apiBase)) + + /** Alias for calling [Builder.apiBase] with `apiBase.orElse(null)`. */ + fun apiBase(apiBase: Optional) = apiBase(apiBase.getOrNull()) + + /** + * Sets [Builder.apiBase] to an arbitrary JSON value. + * + * You should usually call [Builder.apiBase] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiBase(apiBase: JsonField) = apply { this.apiBase = apiBase } + + fun apiKey(apiKey: String?) = apiKey(JsonField.ofNullable(apiKey)) + + /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ + fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) + + /** + * Sets [Builder.apiKey] to an arbitrary JSON value. + * + * You should usually call [Builder.apiKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiKey(apiKey: JsonField) = apply { this.apiKey = apiKey } + + fun apiType(apiType: String?) = apiType(JsonField.ofNullable(apiType)) + + /** Alias for calling [Builder.apiType] with `apiType.orElse(null)`. */ + fun apiType(apiType: Optional) = apiType(apiType.getOrNull()) + + /** + * Sets [Builder.apiType] to an arbitrary JSON value. + * + * You should usually call [Builder.apiType] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiType(apiType: JsonField) = apply { this.apiType = apiType } + + fun apiVersion(apiVersion: String?) = apiVersion(JsonField.ofNullable(apiVersion)) + + /** Alias for calling [Builder.apiVersion] with `apiVersion.orElse(null)`. */ + fun apiVersion(apiVersion: Optional) = apiVersion(apiVersion.getOrNull()) + + /** + * Sets [Builder.apiVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.apiVersion] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiVersion(apiVersion: JsonField) = apply { this.apiVersion = apiVersion } + + fun caching(caching: Boolean) = caching(JsonField.of(caching)) + + /** + * Sets [Builder.caching] to an arbitrary JSON value. + * + * You should usually call [Builder.caching] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun caching(caching: JsonField) = apply { this.caching = caching } + + fun customLlmProvider(customLlmProvider: CustomLlmProvider?) = + customLlmProvider(JsonField.ofNullable(customLlmProvider)) + + /** + * Alias for calling [Builder.customLlmProvider] with `customLlmProvider.orElse(null)`. + */ + fun customLlmProvider(customLlmProvider: Optional) = + customLlmProvider(customLlmProvider.getOrNull()) + + /** + * Sets [Builder.customLlmProvider] to an arbitrary JSON value. + * + * You should usually call [Builder.customLlmProvider] with a well-typed + * [CustomLlmProvider] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun customLlmProvider(customLlmProvider: JsonField) = apply { + this.customLlmProvider = customLlmProvider + } + + /** Alias for calling [customLlmProvider] with `CustomLlmProvider.ofString(string)`. */ + fun customLlmProvider(string: String) = + customLlmProvider(CustomLlmProvider.ofString(string)) + + /** + * Alias for calling [customLlmProvider] with + * `CustomLlmProvider.ofUnionMember1(unionMember1)`. + */ + fun customLlmProvider(unionMember1: CustomLlmProvider.UnionMember1) = + customLlmProvider(CustomLlmProvider.ofUnionMember1(unionMember1)) + + fun input(input: List) = input(JsonField.of(input)) + + /** + * Sets [Builder.input] to an arbitrary JSON value. + * + * You should usually call [Builder.input] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun input(input: JsonField>) = apply { + this.input = input.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [Builder.input]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addInput(input: String) = apply { + this.input = + (this.input ?: JsonField.of(mutableListOf())).also { + checkKnown("input", it).add(input) + } + } + + fun litellmCallId(litellmCallId: String?) = + litellmCallId(JsonField.ofNullable(litellmCallId)) + + /** Alias for calling [Builder.litellmCallId] with `litellmCallId.orElse(null)`. */ + fun litellmCallId(litellmCallId: Optional) = + litellmCallId(litellmCallId.getOrNull()) + + /** + * Sets [Builder.litellmCallId] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmCallId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun litellmCallId(litellmCallId: JsonField) = apply { + this.litellmCallId = litellmCallId + } + + fun litellmLoggingObj(litellmLoggingObj: LitellmLoggingObj?) = + litellmLoggingObj(JsonField.ofNullable(litellmLoggingObj)) + + /** + * Alias for calling [Builder.litellmLoggingObj] with `litellmLoggingObj.orElse(null)`. + */ + fun litellmLoggingObj(litellmLoggingObj: Optional) = + litellmLoggingObj(litellmLoggingObj.getOrNull()) + + /** + * Sets [Builder.litellmLoggingObj] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmLoggingObj] with a well-typed + * [LitellmLoggingObj] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun litellmLoggingObj(litellmLoggingObj: JsonField) = apply { + this.litellmLoggingObj = litellmLoggingObj + } + + fun loggerFn(loggerFn: String?) = loggerFn(JsonField.ofNullable(loggerFn)) + + /** Alias for calling [Builder.loggerFn] with `loggerFn.orElse(null)`. */ + fun loggerFn(loggerFn: Optional) = loggerFn(loggerFn.getOrNull()) + + /** + * Sets [Builder.loggerFn] to an arbitrary JSON value. + * + * You should usually call [Builder.loggerFn] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun loggerFn(loggerFn: JsonField) = apply { this.loggerFn = loggerFn } + + fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun user(user: String?) = user(JsonField.ofNullable(user)) + + /** Alias for calling [Builder.user] with `user.orElse(null)`. */ + fun user(user: Optional) = user(user.getOrNull()) + + /** + * Sets [Builder.user] to an arbitrary JSON value. + * + * You should usually call [Builder.user] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun user(user: JsonField) = apply { this.user = user } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) } - fun removeAdditionalBodyProperty(key: String) = apply { - additionalBodyProperties.remove(key) + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .model() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("model", model), + apiBase, + apiKey, + apiType, + apiVersion, + caching, + customLlmProvider, + (input ?: JsonMissing.of()).map { it.toImmutable() }, + litellmCallId, + litellmLoggingObj, + loggerFn, + timeout, + user, + additionalProperties.toMutableMap(), + ) } - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalBodyProperty) + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + model() + apiBase() + apiKey() + apiType() + apiVersion() + caching() + customLlmProvider().ifPresent { it.validate() } + input() + litellmCallId() + litellmLoggingObj().ifPresent { it.validate() } + loggerFn() + timeout() + user() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + /** - * Returns an immutable instance of [EmbeddingCreateParams]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * Further updates to this [Builder] will not mutate the returned instance. + * Used for best match union deserialization. */ - fun build(): EmbeddingCreateParams = - EmbeddingCreateParams( + @JvmSynthetic + internal fun validity(): Int = + (if (model.asKnown().isPresent) 1 else 0) + + (if (apiBase.asKnown().isPresent) 1 else 0) + + (if (apiKey.asKnown().isPresent) 1 else 0) + + (if (apiType.asKnown().isPresent) 1 else 0) + + (if (apiVersion.asKnown().isPresent) 1 else 0) + + (if (caching.asKnown().isPresent) 1 else 0) + + (customLlmProvider.asKnown().getOrNull()?.validity() ?: 0) + + (input.asKnown().getOrNull()?.size ?: 0) + + (if (litellmCallId.asKnown().isPresent) 1 else 0) + + (litellmLoggingObj.asKnown().getOrNull()?.validity() ?: 0) + + (if (loggerFn.asKnown().isPresent) 1 else 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + (if (user.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + model == other.model && + apiBase == other.apiBase && + apiKey == other.apiKey && + apiType == other.apiType && + apiVersion == other.apiVersion && + caching == other.caching && + customLlmProvider == other.customLlmProvider && + input == other.input && + litellmCallId == other.litellmCallId && + litellmLoggingObj == other.litellmLoggingObj && + loggerFn == other.loggerFn && + timeout == other.timeout && + user == other.user && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( model, - additionalHeaders.build(), - additionalQueryParams.build(), - additionalBodyProperties.toImmutable(), + apiBase, + apiKey, + apiType, + apiVersion, + caching, + customLlmProvider, + input, + litellmCallId, + litellmLoggingObj, + loggerFn, + timeout, + user, + additionalProperties, ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{model=$model, apiBase=$apiBase, apiKey=$apiKey, apiType=$apiType, apiVersion=$apiVersion, caching=$caching, customLlmProvider=$customLlmProvider, input=$input, litellmCallId=$litellmCallId, litellmLoggingObj=$litellmLoggingObj, loggerFn=$loggerFn, timeout=$timeout, user=$user, additionalProperties=$additionalProperties}" } - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + @JsonDeserialize(using = CustomLlmProvider.Deserializer::class) + @JsonSerialize(using = CustomLlmProvider.Serializer::class) + class CustomLlmProvider + private constructor( + private val string: String? = null, + private val unionMember1: UnionMember1? = null, + private val _json: JsonValue? = null, + ) { - override fun _headers(): Headers = additionalHeaders + fun string(): Optional = Optional.ofNullable(string) + + fun unionMember1(): Optional = Optional.ofNullable(unionMember1) + + fun isString(): Boolean = string != null + + fun isUnionMember1(): Boolean = unionMember1 != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnionMember1(): UnionMember1 = unionMember1.getOrThrow("unionMember1") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + unionMember1 != null -> visitor.visitUnionMember1(unionMember1) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): CustomLlmProvider = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitUnionMember1(unionMember1: UnionMember1) { + unionMember1.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitUnionMember1(unionMember1: UnionMember1) = + unionMember1.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomLlmProvider && + string == other.string && + unionMember1 == other.unionMember1 + } + + override fun hashCode(): Int = Objects.hash(string, unionMember1) + + override fun toString(): String = + when { + string != null -> "CustomLlmProvider{string=$string}" + unionMember1 != null -> "CustomLlmProvider{unionMember1=$unionMember1}" + _json != null -> "CustomLlmProvider{_unknown=$_json}" + else -> throw IllegalStateException("Invalid CustomLlmProvider") + } + + companion object { + + @JvmStatic fun ofString(string: String) = CustomLlmProvider(string = string) + + @JvmStatic + fun ofUnionMember1(unionMember1: UnionMember1) = + CustomLlmProvider(unionMember1 = unionMember1) + } + + /** + * An interface that defines how to map each variant of [CustomLlmProvider] to a value of + * type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitUnionMember1(unionMember1: UnionMember1): T + + /** + * Maps an unknown variant of [CustomLlmProvider] to a value of type [T]. + * + * An instance of [CustomLlmProvider] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if the SDK + * is on an older version than the API, then the API may respond with new variants that + * the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown CustomLlmProvider: $json") + } + } + + internal class Deserializer : + BaseDeserializer(CustomLlmProvider::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): CustomLlmProvider { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + CustomLlmProvider(unionMember1 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + CustomLlmProvider(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> CustomLlmProvider(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(CustomLlmProvider::class) { + + override fun serialize( + value: CustomLlmProvider, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unionMember1 != null -> generator.writeObject(value.unionMember1) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid CustomLlmProvider") + } + } + } + + class UnionMember1 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UnionMember1]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember1]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember1: UnionMember1) = apply { + additionalProperties = unionMember1.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } - override fun _queryParams(): QueryParams = - QueryParams.builder() - .apply { - model?.let { put("model", it) } - putAll(additionalQueryParams) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember1]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UnionMember1 = UnionMember1(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember1 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember1 && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "UnionMember1{additionalProperties=$additionalProperties}" + } + } + + class LitellmLoggingObj + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [LitellmLoggingObj]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LitellmLoggingObj]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(litellmLoggingObj: LitellmLoggingObj) = apply { + additionalProperties = litellmLoggingObj.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [LitellmLoggingObj]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): LitellmLoggingObj = LitellmLoggingObj(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): LitellmLoggingObj = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - .build() + + return other is LitellmLoggingObj && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "LitellmLoggingObj{additionalProperties=$additionalProperties}" + } override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is EmbeddingCreateParams && model == other.model && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is EmbeddingCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(model, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) override fun toString() = - "EmbeddingCreateParams{model=$model, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" + "EmbeddingCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/embeddings/EmbeddingCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/embeddings/EmbeddingCreateResponse.kt index 7feb0776..f56be174 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/embeddings/EmbeddingCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/embeddings/EmbeddingCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.embeddings import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class EmbeddingCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun model(): String = model + fun model(): Optional = Optional.ofNullable(model) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [EngineCompleteParams]. - * - * The following fields are required: - * ```java - * .model() - * ``` - */ + @JvmStatic fun none(): EngineCompleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [EngineCompleteParams]. */ @JvmStatic fun builder() = Builder() } @@ -74,7 +72,10 @@ private constructor( additionalBodyProperties = engineCompleteParams.additionalBodyProperties.toMutableMap() } - fun model(model: String) = apply { this.model = model } + fun model(model: String?) = apply { this.model = model } + + /** Alias for calling [Builder.model] with `model.orElse(null)`. */ + fun model(model: Optional) = model(model.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -200,30 +201,22 @@ private constructor( * Returns an immutable instance of [EngineCompleteParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .model() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): EngineCompleteParams = EngineCompleteParams( - checkRequired("model", model), + model, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> model + 0 -> model ?: "" else -> "" } @@ -236,10 +229,15 @@ private constructor( return true } - return /* spotless:off */ other is EngineCompleteParams && model == other.model && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is EngineCompleteParams && + model == other.model && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(model, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(model, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "EngineCompleteParams{model=$model, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/EngineCompleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/EngineCompleteResponse.kt index f71b17a1..ae652209 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/EngineCompleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/EngineCompleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.engines import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class EngineCompleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun model(): String = model + fun pathModel(): Optional = Optional.ofNullable(pathModel) - fun _additionalBodyProperties(): Map = additionalBodyProperties + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun bodyModel(): String = body.bodyModel() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiBase(): Optional = body.apiBase() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiKey(): Optional = body.apiKey() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiType(): Optional = body.apiType() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiVersion(): Optional = body.apiVersion() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun caching(): Optional = body.caching() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customLlmProvider(): Optional = body.customLlmProvider() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun input(): Optional> = body.input() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmCallId(): Optional = body.litellmCallId() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmLoggingObj(): Optional = body.litellmLoggingObj() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun loggerFn(): Optional = body.loggerFn() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = body.timeout() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun user(): Optional = body.user() + + /** + * Returns the raw JSON value of [bodyModel]. + * + * Unlike [bodyModel], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _bodyModel(): JsonField = body._bodyModel() + + /** + * Returns the raw JSON value of [apiBase]. + * + * Unlike [apiBase], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _apiBase(): JsonField = body._apiBase() + + /** + * Returns the raw JSON value of [apiKey]. + * + * Unlike [apiKey], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _apiKey(): JsonField = body._apiKey() + + /** + * Returns the raw JSON value of [apiType]. + * + * Unlike [apiType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _apiType(): JsonField = body._apiType() + + /** + * Returns the raw JSON value of [apiVersion]. + * + * Unlike [apiVersion], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _apiVersion(): JsonField = body._apiVersion() + + /** + * Returns the raw JSON value of [caching]. + * + * Unlike [caching], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _caching(): JsonField = body._caching() + + /** + * Returns the raw JSON value of [customLlmProvider]. + * + * Unlike [customLlmProvider], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _customLlmProvider(): JsonField = body._customLlmProvider() + + /** + * Returns the raw JSON value of [input]. + * + * Unlike [input], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _input(): JsonField> = body._input() + + /** + * Returns the raw JSON value of [litellmCallId]. + * + * Unlike [litellmCallId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _litellmCallId(): JsonField = body._litellmCallId() + + /** + * Returns the raw JSON value of [litellmLoggingObj]. + * + * Unlike [litellmLoggingObj], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _litellmLoggingObj(): JsonField = body._litellmLoggingObj() + + /** + * Returns the raw JSON value of [loggerFn]. + * + * Unlike [loggerFn], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _loggerFn(): JsonField = body._loggerFn() + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _timeout(): JsonField = body._timeout() + + /** + * Returns the raw JSON value of [user]. + * + * Unlike [user], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _user(): JsonField = body._user() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -50,7 +245,7 @@ private constructor( * * The following fields are required: * ```java - * .model() + * .bodyModel() * ``` */ @JvmStatic fun builder() = Builder() @@ -59,20 +254,250 @@ private constructor( /** A builder for [EngineEmbedParams]. */ class Builder internal constructor() { - private var model: String? = null + private var pathModel: String? = null + private var body: Body.Builder = Body.builder() private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(engineEmbedParams: EngineEmbedParams) = apply { - model = engineEmbedParams.model + pathModel = engineEmbedParams.pathModel + body = engineEmbedParams.body.toBuilder() additionalHeaders = engineEmbedParams.additionalHeaders.toBuilder() additionalQueryParams = engineEmbedParams.additionalQueryParams.toBuilder() - additionalBodyProperties = engineEmbedParams.additionalBodyProperties.toMutableMap() } - fun model(model: String) = apply { this.model = model } + fun pathModel(pathModel: String?) = apply { this.pathModel = pathModel } + + /** Alias for calling [Builder.pathModel] with `pathModel.orElse(null)`. */ + fun pathModel(pathModel: Optional) = pathModel(pathModel.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [bodyModel] + * - [apiBase] + * - [apiKey] + * - [apiType] + * - [apiVersion] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + fun bodyModel(bodyModel: String) = apply { body.bodyModel(bodyModel) } + + /** + * Sets [Builder.bodyModel] to an arbitrary JSON value. + * + * You should usually call [Builder.bodyModel] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun bodyModel(bodyModel: JsonField) = apply { body.bodyModel(bodyModel) } + + fun apiBase(apiBase: String?) = apply { body.apiBase(apiBase) } + + /** Alias for calling [Builder.apiBase] with `apiBase.orElse(null)`. */ + fun apiBase(apiBase: Optional) = apiBase(apiBase.getOrNull()) + + /** + * Sets [Builder.apiBase] to an arbitrary JSON value. + * + * You should usually call [Builder.apiBase] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun apiBase(apiBase: JsonField) = apply { body.apiBase(apiBase) } + + fun apiKey(apiKey: String?) = apply { body.apiKey(apiKey) } + + /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ + fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) + + /** + * Sets [Builder.apiKey] to an arbitrary JSON value. + * + * You should usually call [Builder.apiKey] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun apiKey(apiKey: JsonField) = apply { body.apiKey(apiKey) } + + fun apiType(apiType: String?) = apply { body.apiType(apiType) } + + /** Alias for calling [Builder.apiType] with `apiType.orElse(null)`. */ + fun apiType(apiType: Optional) = apiType(apiType.getOrNull()) + + /** + * Sets [Builder.apiType] to an arbitrary JSON value. + * + * You should usually call [Builder.apiType] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun apiType(apiType: JsonField) = apply { body.apiType(apiType) } + + fun apiVersion(apiVersion: String?) = apply { body.apiVersion(apiVersion) } + + /** Alias for calling [Builder.apiVersion] with `apiVersion.orElse(null)`. */ + fun apiVersion(apiVersion: Optional) = apiVersion(apiVersion.getOrNull()) + + /** + * Sets [Builder.apiVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.apiVersion] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun apiVersion(apiVersion: JsonField) = apply { body.apiVersion(apiVersion) } + + fun caching(caching: Boolean) = apply { body.caching(caching) } + + /** + * Sets [Builder.caching] to an arbitrary JSON value. + * + * You should usually call [Builder.caching] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun caching(caching: JsonField) = apply { body.caching(caching) } + + fun customLlmProvider(customLlmProvider: CustomLlmProvider?) = apply { + body.customLlmProvider(customLlmProvider) + } + + /** Alias for calling [Builder.customLlmProvider] with `customLlmProvider.orElse(null)`. */ + fun customLlmProvider(customLlmProvider: Optional) = + customLlmProvider(customLlmProvider.getOrNull()) + + /** + * Sets [Builder.customLlmProvider] to an arbitrary JSON value. + * + * You should usually call [Builder.customLlmProvider] with a well-typed [CustomLlmProvider] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun customLlmProvider(customLlmProvider: JsonField) = apply { + body.customLlmProvider(customLlmProvider) + } + + /** Alias for calling [customLlmProvider] with `CustomLlmProvider.ofString(string)`. */ + fun customLlmProvider(string: String) = apply { body.customLlmProvider(string) } + + /** + * Alias for calling [customLlmProvider] with + * `CustomLlmProvider.ofUnionMember1(unionMember1)`. + */ + fun customLlmProvider(unionMember1: CustomLlmProvider.UnionMember1) = apply { + body.customLlmProvider(unionMember1) + } + + fun input(input: List) = apply { body.input(input) } + + /** + * Sets [Builder.input] to an arbitrary JSON value. + * + * You should usually call [Builder.input] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun input(input: JsonField>) = apply { body.input(input) } + + /** + * Adds a single [String] to [Builder.input]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addInput(input: String) = apply { body.addInput(input) } + + fun litellmCallId(litellmCallId: String?) = apply { body.litellmCallId(litellmCallId) } + + /** Alias for calling [Builder.litellmCallId] with `litellmCallId.orElse(null)`. */ + fun litellmCallId(litellmCallId: Optional) = + litellmCallId(litellmCallId.getOrNull()) + + /** + * Sets [Builder.litellmCallId] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmCallId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun litellmCallId(litellmCallId: JsonField) = apply { + body.litellmCallId(litellmCallId) + } + + fun litellmLoggingObj(litellmLoggingObj: LitellmLoggingObj?) = apply { + body.litellmLoggingObj(litellmLoggingObj) + } + + /** Alias for calling [Builder.litellmLoggingObj] with `litellmLoggingObj.orElse(null)`. */ + fun litellmLoggingObj(litellmLoggingObj: Optional) = + litellmLoggingObj(litellmLoggingObj.getOrNull()) + + /** + * Sets [Builder.litellmLoggingObj] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmLoggingObj] with a well-typed [LitellmLoggingObj] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun litellmLoggingObj(litellmLoggingObj: JsonField) = apply { + body.litellmLoggingObj(litellmLoggingObj) + } + + fun loggerFn(loggerFn: String?) = apply { body.loggerFn(loggerFn) } + + /** Alias for calling [Builder.loggerFn] with `loggerFn.orElse(null)`. */ + fun loggerFn(loggerFn: Optional) = loggerFn(loggerFn.getOrNull()) + + /** + * Sets [Builder.loggerFn] to an arbitrary JSON value. + * + * You should usually call [Builder.loggerFn] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun loggerFn(loggerFn: JsonField) = apply { body.loggerFn(loggerFn) } + + fun timeout(timeout: Long) = apply { body.timeout(timeout) } + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun timeout(timeout: JsonField) = apply { body.timeout(timeout) } + + fun user(user: String?) = apply { body.user(user) } + + /** Alias for calling [Builder.user] with `user.orElse(null)`. */ + fun user(user: Optional) = user(user.getOrNull()) + + /** + * Sets [Builder.user] to an arbitrary JSON value. + * + * You should usually call [Builder.user] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun user(user: JsonField) = apply { body.user(user) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -172,28 +597,6 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - putAllAdditionalBodyProperties(additionalBodyProperties) - } - - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - additionalBodyProperties.put(key, value) - } - - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - - fun removeAdditionalBodyProperty(key: String) = apply { - additionalBodyProperties.remove(key) - } - - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalBodyProperty) - } - /** * Returns an immutable instance of [EngineEmbedParams]. * @@ -201,27 +604,25 @@ private constructor( * * The following fields are required: * ```java - * .model() + * .bodyModel() * ``` * * @throws IllegalStateException if any required field is unset. */ fun build(): EngineEmbedParams = EngineEmbedParams( - checkRequired("model", model), + pathModel, + body.build(), additionalHeaders.build(), additionalQueryParams.build(), - additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + fun _body(): Body = body fun _pathParam(index: Int): String = when (index) { - 0 -> model + 0 -> pathModel ?: "" else -> "" } @@ -229,16 +630,1067 @@ private constructor( override fun _queryParams(): QueryParams = additionalQueryParams + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val bodyModel: JsonField, + private val apiBase: JsonField, + private val apiKey: JsonField, + private val apiType: JsonField, + private val apiVersion: JsonField, + private val caching: JsonField, + private val customLlmProvider: JsonField, + private val input: JsonField>, + private val litellmCallId: JsonField, + private val litellmLoggingObj: JsonField, + private val loggerFn: JsonField, + private val timeout: JsonField, + private val user: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("model") @ExcludeMissing bodyModel: JsonField = JsonMissing.of(), + @JsonProperty("api_base") @ExcludeMissing apiBase: JsonField = JsonMissing.of(), + @JsonProperty("api_key") @ExcludeMissing apiKey: JsonField = JsonMissing.of(), + @JsonProperty("api_type") @ExcludeMissing apiType: JsonField = JsonMissing.of(), + @JsonProperty("api_version") + @ExcludeMissing + apiVersion: JsonField = JsonMissing.of(), + @JsonProperty("caching") @ExcludeMissing caching: JsonField = JsonMissing.of(), + @JsonProperty("custom_llm_provider") + @ExcludeMissing + customLlmProvider: JsonField = JsonMissing.of(), + @JsonProperty("input") + @ExcludeMissing + input: JsonField> = JsonMissing.of(), + @JsonProperty("litellm_call_id") + @ExcludeMissing + litellmCallId: JsonField = JsonMissing.of(), + @JsonProperty("litellm_logging_obj") + @ExcludeMissing + litellmLoggingObj: JsonField = JsonMissing.of(), + @JsonProperty("logger_fn") + @ExcludeMissing + loggerFn: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + @JsonProperty("user") @ExcludeMissing user: JsonField = JsonMissing.of(), + ) : this( + bodyModel, + apiBase, + apiKey, + apiType, + apiVersion, + caching, + customLlmProvider, + input, + litellmCallId, + litellmLoggingObj, + loggerFn, + timeout, + user, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun bodyModel(): String = bodyModel.getRequired("model") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiBase(): Optional = apiBase.getOptional("api_base") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiKey(): Optional = apiKey.getOptional("api_key") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiType(): Optional = apiType.getOptional("api_type") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiVersion(): Optional = apiVersion.getOptional("api_version") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun caching(): Optional = caching.getOptional("caching") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customLlmProvider(): Optional = + customLlmProvider.getOptional("custom_llm_provider") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun input(): Optional> = input.getOptional("input") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmCallId(): Optional = litellmCallId.getOptional("litellm_call_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmLoggingObj(): Optional = + litellmLoggingObj.getOptional("litellm_logging_obj") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun loggerFn(): Optional = loggerFn.getOptional("logger_fn") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = timeout.getOptional("timeout") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun user(): Optional = user.getOptional("user") + + /** + * Returns the raw JSON value of [bodyModel]. + * + * Unlike [bodyModel], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _bodyModel(): JsonField = bodyModel + + /** + * Returns the raw JSON value of [apiBase]. + * + * Unlike [apiBase], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_base") @ExcludeMissing fun _apiBase(): JsonField = apiBase + + /** + * Returns the raw JSON value of [apiKey]. + * + * Unlike [apiKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_key") @ExcludeMissing fun _apiKey(): JsonField = apiKey + + /** + * Returns the raw JSON value of [apiType]. + * + * Unlike [apiType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_type") @ExcludeMissing fun _apiType(): JsonField = apiType + + /** + * Returns the raw JSON value of [apiVersion]. + * + * Unlike [apiVersion], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_version") + @ExcludeMissing + fun _apiVersion(): JsonField = apiVersion + + /** + * Returns the raw JSON value of [caching]. + * + * Unlike [caching], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("caching") @ExcludeMissing fun _caching(): JsonField = caching + + /** + * Returns the raw JSON value of [customLlmProvider]. + * + * Unlike [customLlmProvider], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("custom_llm_provider") + @ExcludeMissing + fun _customLlmProvider(): JsonField = customLlmProvider + + /** + * Returns the raw JSON value of [input]. + * + * Unlike [input], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonField> = input + + /** + * Returns the raw JSON value of [litellmCallId]. + * + * Unlike [litellmCallId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("litellm_call_id") + @ExcludeMissing + fun _litellmCallId(): JsonField = litellmCallId + + /** + * Returns the raw JSON value of [litellmLoggingObj]. + * + * Unlike [litellmLoggingObj], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("litellm_logging_obj") + @ExcludeMissing + fun _litellmLoggingObj(): JsonField = litellmLoggingObj + + /** + * Returns the raw JSON value of [loggerFn]. + * + * Unlike [loggerFn], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("logger_fn") @ExcludeMissing fun _loggerFn(): JsonField = loggerFn + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + /** + * Returns the raw JSON value of [user]. + * + * Unlike [user], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user") @ExcludeMissing fun _user(): JsonField = user + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .bodyModel() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var bodyModel: JsonField? = null + private var apiBase: JsonField = JsonMissing.of() + private var apiKey: JsonField = JsonMissing.of() + private var apiType: JsonField = JsonMissing.of() + private var apiVersion: JsonField = JsonMissing.of() + private var caching: JsonField = JsonMissing.of() + private var customLlmProvider: JsonField = JsonMissing.of() + private var input: JsonField>? = null + private var litellmCallId: JsonField = JsonMissing.of() + private var litellmLoggingObj: JsonField = JsonMissing.of() + private var loggerFn: JsonField = JsonMissing.of() + private var timeout: JsonField = JsonMissing.of() + private var user: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + bodyModel = body.bodyModel + apiBase = body.apiBase + apiKey = body.apiKey + apiType = body.apiType + apiVersion = body.apiVersion + caching = body.caching + customLlmProvider = body.customLlmProvider + input = body.input.map { it.toMutableList() } + litellmCallId = body.litellmCallId + litellmLoggingObj = body.litellmLoggingObj + loggerFn = body.loggerFn + timeout = body.timeout + user = body.user + additionalProperties = body.additionalProperties.toMutableMap() + } + + fun bodyModel(bodyModel: String) = bodyModel(JsonField.of(bodyModel)) + + /** + * Sets [Builder.bodyModel] to an arbitrary JSON value. + * + * You should usually call [Builder.bodyModel] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun bodyModel(bodyModel: JsonField) = apply { this.bodyModel = bodyModel } + + fun apiBase(apiBase: String?) = apiBase(JsonField.ofNullable(apiBase)) + + /** Alias for calling [Builder.apiBase] with `apiBase.orElse(null)`. */ + fun apiBase(apiBase: Optional) = apiBase(apiBase.getOrNull()) + + /** + * Sets [Builder.apiBase] to an arbitrary JSON value. + * + * You should usually call [Builder.apiBase] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiBase(apiBase: JsonField) = apply { this.apiBase = apiBase } + + fun apiKey(apiKey: String?) = apiKey(JsonField.ofNullable(apiKey)) + + /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ + fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) + + /** + * Sets [Builder.apiKey] to an arbitrary JSON value. + * + * You should usually call [Builder.apiKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiKey(apiKey: JsonField) = apply { this.apiKey = apiKey } + + fun apiType(apiType: String?) = apiType(JsonField.ofNullable(apiType)) + + /** Alias for calling [Builder.apiType] with `apiType.orElse(null)`. */ + fun apiType(apiType: Optional) = apiType(apiType.getOrNull()) + + /** + * Sets [Builder.apiType] to an arbitrary JSON value. + * + * You should usually call [Builder.apiType] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiType(apiType: JsonField) = apply { this.apiType = apiType } + + fun apiVersion(apiVersion: String?) = apiVersion(JsonField.ofNullable(apiVersion)) + + /** Alias for calling [Builder.apiVersion] with `apiVersion.orElse(null)`. */ + fun apiVersion(apiVersion: Optional) = apiVersion(apiVersion.getOrNull()) + + /** + * Sets [Builder.apiVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.apiVersion] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiVersion(apiVersion: JsonField) = apply { this.apiVersion = apiVersion } + + fun caching(caching: Boolean) = caching(JsonField.of(caching)) + + /** + * Sets [Builder.caching] to an arbitrary JSON value. + * + * You should usually call [Builder.caching] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun caching(caching: JsonField) = apply { this.caching = caching } + + fun customLlmProvider(customLlmProvider: CustomLlmProvider?) = + customLlmProvider(JsonField.ofNullable(customLlmProvider)) + + /** + * Alias for calling [Builder.customLlmProvider] with `customLlmProvider.orElse(null)`. + */ + fun customLlmProvider(customLlmProvider: Optional) = + customLlmProvider(customLlmProvider.getOrNull()) + + /** + * Sets [Builder.customLlmProvider] to an arbitrary JSON value. + * + * You should usually call [Builder.customLlmProvider] with a well-typed + * [CustomLlmProvider] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun customLlmProvider(customLlmProvider: JsonField) = apply { + this.customLlmProvider = customLlmProvider + } + + /** Alias for calling [customLlmProvider] with `CustomLlmProvider.ofString(string)`. */ + fun customLlmProvider(string: String) = + customLlmProvider(CustomLlmProvider.ofString(string)) + + /** + * Alias for calling [customLlmProvider] with + * `CustomLlmProvider.ofUnionMember1(unionMember1)`. + */ + fun customLlmProvider(unionMember1: CustomLlmProvider.UnionMember1) = + customLlmProvider(CustomLlmProvider.ofUnionMember1(unionMember1)) + + fun input(input: List) = input(JsonField.of(input)) + + /** + * Sets [Builder.input] to an arbitrary JSON value. + * + * You should usually call [Builder.input] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun input(input: JsonField>) = apply { + this.input = input.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [Builder.input]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addInput(input: String) = apply { + this.input = + (this.input ?: JsonField.of(mutableListOf())).also { + checkKnown("input", it).add(input) + } + } + + fun litellmCallId(litellmCallId: String?) = + litellmCallId(JsonField.ofNullable(litellmCallId)) + + /** Alias for calling [Builder.litellmCallId] with `litellmCallId.orElse(null)`. */ + fun litellmCallId(litellmCallId: Optional) = + litellmCallId(litellmCallId.getOrNull()) + + /** + * Sets [Builder.litellmCallId] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmCallId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun litellmCallId(litellmCallId: JsonField) = apply { + this.litellmCallId = litellmCallId + } + + fun litellmLoggingObj(litellmLoggingObj: LitellmLoggingObj?) = + litellmLoggingObj(JsonField.ofNullable(litellmLoggingObj)) + + /** + * Alias for calling [Builder.litellmLoggingObj] with `litellmLoggingObj.orElse(null)`. + */ + fun litellmLoggingObj(litellmLoggingObj: Optional) = + litellmLoggingObj(litellmLoggingObj.getOrNull()) + + /** + * Sets [Builder.litellmLoggingObj] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmLoggingObj] with a well-typed + * [LitellmLoggingObj] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun litellmLoggingObj(litellmLoggingObj: JsonField) = apply { + this.litellmLoggingObj = litellmLoggingObj + } + + fun loggerFn(loggerFn: String?) = loggerFn(JsonField.ofNullable(loggerFn)) + + /** Alias for calling [Builder.loggerFn] with `loggerFn.orElse(null)`. */ + fun loggerFn(loggerFn: Optional) = loggerFn(loggerFn.getOrNull()) + + /** + * Sets [Builder.loggerFn] to an arbitrary JSON value. + * + * You should usually call [Builder.loggerFn] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun loggerFn(loggerFn: JsonField) = apply { this.loggerFn = loggerFn } + + fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun user(user: String?) = user(JsonField.ofNullable(user)) + + /** Alias for calling [Builder.user] with `user.orElse(null)`. */ + fun user(user: Optional) = user(user.getOrNull()) + + /** + * Sets [Builder.user] to an arbitrary JSON value. + * + * You should usually call [Builder.user] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun user(user: JsonField) = apply { this.user = user } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .bodyModel() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("bodyModel", bodyModel), + apiBase, + apiKey, + apiType, + apiVersion, + caching, + customLlmProvider, + (input ?: JsonMissing.of()).map { it.toImmutable() }, + litellmCallId, + litellmLoggingObj, + loggerFn, + timeout, + user, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + bodyModel() + apiBase() + apiKey() + apiType() + apiVersion() + caching() + customLlmProvider().ifPresent { it.validate() } + input() + litellmCallId() + litellmLoggingObj().ifPresent { it.validate() } + loggerFn() + timeout() + user() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (bodyModel.asKnown().isPresent) 1 else 0) + + (if (apiBase.asKnown().isPresent) 1 else 0) + + (if (apiKey.asKnown().isPresent) 1 else 0) + + (if (apiType.asKnown().isPresent) 1 else 0) + + (if (apiVersion.asKnown().isPresent) 1 else 0) + + (if (caching.asKnown().isPresent) 1 else 0) + + (customLlmProvider.asKnown().getOrNull()?.validity() ?: 0) + + (input.asKnown().getOrNull()?.size ?: 0) + + (if (litellmCallId.asKnown().isPresent) 1 else 0) + + (litellmLoggingObj.asKnown().getOrNull()?.validity() ?: 0) + + (if (loggerFn.asKnown().isPresent) 1 else 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + (if (user.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + bodyModel == other.bodyModel && + apiBase == other.apiBase && + apiKey == other.apiKey && + apiType == other.apiType && + apiVersion == other.apiVersion && + caching == other.caching && + customLlmProvider == other.customLlmProvider && + input == other.input && + litellmCallId == other.litellmCallId && + litellmLoggingObj == other.litellmLoggingObj && + loggerFn == other.loggerFn && + timeout == other.timeout && + user == other.user && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + bodyModel, + apiBase, + apiKey, + apiType, + apiVersion, + caching, + customLlmProvider, + input, + litellmCallId, + litellmLoggingObj, + loggerFn, + timeout, + user, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{bodyModel=$bodyModel, apiBase=$apiBase, apiKey=$apiKey, apiType=$apiType, apiVersion=$apiVersion, caching=$caching, customLlmProvider=$customLlmProvider, input=$input, litellmCallId=$litellmCallId, litellmLoggingObj=$litellmLoggingObj, loggerFn=$loggerFn, timeout=$timeout, user=$user, additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = CustomLlmProvider.Deserializer::class) + @JsonSerialize(using = CustomLlmProvider.Serializer::class) + class CustomLlmProvider + private constructor( + private val string: String? = null, + private val unionMember1: UnionMember1? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun unionMember1(): Optional = Optional.ofNullable(unionMember1) + + fun isString(): Boolean = string != null + + fun isUnionMember1(): Boolean = unionMember1 != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnionMember1(): UnionMember1 = unionMember1.getOrThrow("unionMember1") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + unionMember1 != null -> visitor.visitUnionMember1(unionMember1) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): CustomLlmProvider = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitUnionMember1(unionMember1: UnionMember1) { + unionMember1.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitUnionMember1(unionMember1: UnionMember1) = + unionMember1.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomLlmProvider && + string == other.string && + unionMember1 == other.unionMember1 + } + + override fun hashCode(): Int = Objects.hash(string, unionMember1) + + override fun toString(): String = + when { + string != null -> "CustomLlmProvider{string=$string}" + unionMember1 != null -> "CustomLlmProvider{unionMember1=$unionMember1}" + _json != null -> "CustomLlmProvider{_unknown=$_json}" + else -> throw IllegalStateException("Invalid CustomLlmProvider") + } + + companion object { + + @JvmStatic fun ofString(string: String) = CustomLlmProvider(string = string) + + @JvmStatic + fun ofUnionMember1(unionMember1: UnionMember1) = + CustomLlmProvider(unionMember1 = unionMember1) + } + + /** + * An interface that defines how to map each variant of [CustomLlmProvider] to a value of + * type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitUnionMember1(unionMember1: UnionMember1): T + + /** + * Maps an unknown variant of [CustomLlmProvider] to a value of type [T]. + * + * An instance of [CustomLlmProvider] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if the SDK + * is on an older version than the API, then the API may respond with new variants that + * the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown CustomLlmProvider: $json") + } + } + + internal class Deserializer : + BaseDeserializer(CustomLlmProvider::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): CustomLlmProvider { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + CustomLlmProvider(unionMember1 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + CustomLlmProvider(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> CustomLlmProvider(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(CustomLlmProvider::class) { + + override fun serialize( + value: CustomLlmProvider, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unionMember1 != null -> generator.writeObject(value.unionMember1) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid CustomLlmProvider") + } + } + } + + class UnionMember1 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UnionMember1]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember1]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember1: UnionMember1) = apply { + additionalProperties = unionMember1.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember1]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UnionMember1 = UnionMember1(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember1 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember1 && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "UnionMember1{additionalProperties=$additionalProperties}" + } + } + + class LitellmLoggingObj + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [LitellmLoggingObj]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LitellmLoggingObj]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(litellmLoggingObj: LitellmLoggingObj) = apply { + additionalProperties = litellmLoggingObj.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [LitellmLoggingObj]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): LitellmLoggingObj = LitellmLoggingObj(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): LitellmLoggingObj = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is LitellmLoggingObj && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "LitellmLoggingObj{additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is EngineEmbedParams && model == other.model && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is EngineEmbedParams && + pathModel == other.pathModel && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(model, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(pathModel, body, additionalHeaders, additionalQueryParams) override fun toString() = - "EngineEmbedParams{model=$model, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" + "EngineEmbedParams{pathModel=$pathModel, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/EngineEmbedResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/EngineEmbedResponse.kt index 3b1e0c6c..aa81ac76 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/EngineEmbedResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/EngineEmbedResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.engines import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class EngineEmbedResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun model(): String = model + fun pathModel(): Optional = Optional.ofNullable(pathModel) - fun _additionalBodyProperties(): Map = additionalBodyProperties + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun messages(): List = body.messages() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun bodyModel(): String = body.bodyModel() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun caching(): Optional = body.caching() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun contextWindowFallbackDict(): Optional = + body.contextWindowFallbackDict() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fallbacks(): Optional> = body.fallbacks() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun frequencyPenalty(): Optional = body.frequencyPenalty() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functionCall(): Optional = body.functionCall() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functions(): Optional> = body.functions() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun guardrails(): Optional> = body.guardrails() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logitBias(): Optional = body.logitBias() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logprobs(): Optional = body.logprobs() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxTokens(): Optional = body.maxTokens() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = body.metadata() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun n(): Optional = body.n() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun numRetries(): Optional = body.numRetries() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun parallelToolCalls(): Optional = body.parallelToolCalls() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun presencePenalty(): Optional = body.presencePenalty() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun responseFormat(): Optional = body.responseFormat() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun seed(): Optional = body.seed() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun serviceTier(): Optional = body.serviceTier() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stop(): Optional = body.stop() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stream(): Optional = body.stream() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun streamOptions(): Optional = body.streamOptions() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun temperature(): Optional = body.temperature() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolChoice(): Optional = body.toolChoice() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tools(): Optional> = body.tools() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun topLogprobs(): Optional = body.topLogprobs() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun topP(): Optional = body.topP() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun user(): Optional = body.user() + + /** + * Returns the raw JSON value of [messages]. + * + * Unlike [messages], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _messages(): JsonField> = body._messages() + + /** + * Returns the raw JSON value of [bodyModel]. + * + * Unlike [bodyModel], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _bodyModel(): JsonField = body._bodyModel() + + /** + * Returns the raw JSON value of [caching]. + * + * Unlike [caching], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _caching(): JsonField = body._caching() + + /** + * Returns the raw JSON value of [contextWindowFallbackDict]. + * + * Unlike [contextWindowFallbackDict], this method doesn't throw if the JSON field has an + * unexpected type. + */ + fun _contextWindowFallbackDict(): JsonField = + body._contextWindowFallbackDict() + + /** + * Returns the raw JSON value of [fallbacks]. + * + * Unlike [fallbacks], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _fallbacks(): JsonField> = body._fallbacks() + + /** + * Returns the raw JSON value of [frequencyPenalty]. + * + * Unlike [frequencyPenalty], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _frequencyPenalty(): JsonField = body._frequencyPenalty() + + /** + * Returns the raw JSON value of [functionCall]. + * + * Unlike [functionCall], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functionCall(): JsonField = body._functionCall() + + /** + * Returns the raw JSON value of [functions]. + * + * Unlike [functions], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functions(): JsonField> = body._functions() + + /** + * Returns the raw JSON value of [guardrails]. + * + * Unlike [guardrails], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _guardrails(): JsonField> = body._guardrails() + + /** + * Returns the raw JSON value of [logitBias]. + * + * Unlike [logitBias], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _logitBias(): JsonField = body._logitBias() + + /** + * Returns the raw JSON value of [logprobs]. + * + * Unlike [logprobs], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _logprobs(): JsonField = body._logprobs() + + /** + * Returns the raw JSON value of [maxTokens]. + * + * Unlike [maxTokens], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _maxTokens(): JsonField = body._maxTokens() + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [n]. + * + * Unlike [n], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _n(): JsonField = body._n() + + /** + * Returns the raw JSON value of [numRetries]. + * + * Unlike [numRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _numRetries(): JsonField = body._numRetries() + + /** + * Returns the raw JSON value of [parallelToolCalls]. + * + * Unlike [parallelToolCalls], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _parallelToolCalls(): JsonField = body._parallelToolCalls() + + /** + * Returns the raw JSON value of [presencePenalty]. + * + * Unlike [presencePenalty], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _presencePenalty(): JsonField = body._presencePenalty() + + /** + * Returns the raw JSON value of [responseFormat]. + * + * Unlike [responseFormat], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _responseFormat(): JsonField = body._responseFormat() + + /** + * Returns the raw JSON value of [seed]. + * + * Unlike [seed], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _seed(): JsonField = body._seed() + + /** + * Returns the raw JSON value of [serviceTier]. + * + * Unlike [serviceTier], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _serviceTier(): JsonField = body._serviceTier() + + /** + * Returns the raw JSON value of [stop]. + * + * Unlike [stop], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _stop(): JsonField = body._stop() + + /** + * Returns the raw JSON value of [stream]. + * + * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _stream(): JsonField = body._stream() + + /** + * Returns the raw JSON value of [streamOptions]. + * + * Unlike [streamOptions], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _streamOptions(): JsonField = body._streamOptions() + + /** + * Returns the raw JSON value of [temperature]. + * + * Unlike [temperature], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _temperature(): JsonField = body._temperature() + + /** + * Returns the raw JSON value of [toolChoice]. + * + * Unlike [toolChoice], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _toolChoice(): JsonField = body._toolChoice() + + /** + * Returns the raw JSON value of [tools]. + * + * Unlike [tools], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tools(): JsonField> = body._tools() + + /** + * Returns the raw JSON value of [topLogprobs]. + * + * Unlike [topLogprobs], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _topLogprobs(): JsonField = body._topLogprobs() + + /** + * Returns the raw JSON value of [topP]. + * + * Unlike [topP], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _topP(): JsonField = body._topP() + + /** + * Returns the raw JSON value of [user]. + * + * Unlike [user], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _user(): JsonField = body._user() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -55,7 +462,8 @@ private constructor( * * The following fields are required: * ```java - * .model() + * .messages() + * .bodyModel() * ``` */ @JvmStatic fun builder() = Builder() @@ -64,186 +472,16464 @@ private constructor( /** A builder for [ChatCompleteParams]. */ class Builder internal constructor() { - private var model: String? = null + private var pathModel: String? = null + private var body: Body.Builder = Body.builder() private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(chatCompleteParams: ChatCompleteParams) = apply { - model = chatCompleteParams.model + pathModel = chatCompleteParams.pathModel + body = chatCompleteParams.body.toBuilder() additionalHeaders = chatCompleteParams.additionalHeaders.toBuilder() additionalQueryParams = chatCompleteParams.additionalQueryParams.toBuilder() - additionalBodyProperties = chatCompleteParams.additionalBodyProperties.toMutableMap() } - fun model(model: String) = apply { this.model = model } + fun pathModel(pathModel: String?) = apply { this.pathModel = pathModel } - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Alias for calling [Builder.pathModel] with `pathModel.orElse(null)`. */ + fun pathModel(pathModel: Optional) = pathModel(pathModel.getOrNull()) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [messages] + * - [bodyModel] + * - [caching] + * - [contextWindowFallbackDict] + * - [fallbacks] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + fun messages(messages: List) = apply { body.messages(messages) } - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Sets [Builder.messages] to an arbitrary JSON value. + * + * You should usually call [Builder.messages] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun messages(messages: JsonField>) = apply { body.messages(messages) } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Adds a single [Message] to [messages]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMessage(message: Message) = apply { body.addMessage(message) } - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) + /** + * Alias for calling [addMessage] with `Message.ofChatCompletionUser(chatCompletionUser)`. + */ + fun addMessage(chatCompletionUser: Message.ChatCompletionUserMessage) = apply { + body.addMessage(chatCompletionUser) } - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionAssistant(chatCompletionAssistant)`. + */ + fun addMessage(chatCompletionAssistant: Message.ChatCompletionAssistantMessage) = apply { + body.addMessage(chatCompletionAssistant) } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) + /** + * Alias for calling [addMessage] with `Message.ofChatCompletionTool(chatCompletionTool)`. + */ + fun addMessage(chatCompletionTool: Message.ChatCompletionToolMessage) = apply { + body.addMessage(chatCompletionTool) } - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionSystem(chatCompletionSystem)`. + */ + fun addMessage(chatCompletionSystem: Message.ChatCompletionSystemMessage) = apply { + body.addMessage(chatCompletionSystem) } - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionFunction(chatCompletionFunction)`. + */ + fun addMessage(chatCompletionFunction: Message.ChatCompletionFunctionMessage) = apply { + body.addMessage(chatCompletionFunction) } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionDeveloper(chatCompletionDeveloper)`. + */ + fun addMessage(chatCompletionDeveloper: Message.ChatCompletionDeveloperMessage) = apply { + body.addMessage(chatCompletionDeveloper) } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun bodyModel(bodyModel: String) = apply { body.bodyModel(bodyModel) } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.bodyModel] to an arbitrary JSON value. + * + * You should usually call [Builder.bodyModel] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun bodyModel(bodyModel: JsonField) = apply { body.bodyModel(bodyModel) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun caching(caching: Boolean?) = apply { body.caching(caching) } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + /** + * Alias for [Builder.caching]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun caching(caching: Boolean) = caching(caching as Boolean?) - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + /** Alias for calling [Builder.caching] with `caching.orElse(null)`. */ + fun caching(caching: Optional) = caching(caching.getOrNull()) - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + /** + * Sets [Builder.caching] to an arbitrary JSON value. + * + * You should usually call [Builder.caching] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun caching(caching: JsonField) = apply { body.caching(caching) } + + fun contextWindowFallbackDict(contextWindowFallbackDict: ContextWindowFallbackDict?) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) + body.contextWindowFallbackDict(contextWindowFallbackDict) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } + /** + * Alias for calling [Builder.contextWindowFallbackDict] with + * `contextWindowFallbackDict.orElse(null)`. + */ + fun contextWindowFallbackDict( + contextWindowFallbackDict: Optional + ) = contextWindowFallbackDict(contextWindowFallbackDict.getOrNull()) - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + /** + * Sets [Builder.contextWindowFallbackDict] to an arbitrary JSON value. + * + * You should usually call [Builder.contextWindowFallbackDict] with a well-typed + * [ContextWindowFallbackDict] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun contextWindowFallbackDict( + contextWindowFallbackDict: JsonField + ) = apply { body.contextWindowFallbackDict(contextWindowFallbackDict) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + fun fallbacks(fallbacks: List?) = apply { body.fallbacks(fallbacks) } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** Alias for calling [Builder.fallbacks] with `fallbacks.orElse(null)`. */ + fun fallbacks(fallbacks: Optional>) = fallbacks(fallbacks.getOrNull()) - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /** + * Sets [Builder.fallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.fallbacks] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fallbacks(fallbacks: JsonField>) = apply { body.fallbacks(fallbacks) } - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } + /** + * Adds a single [String] to [fallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFallback(fallback: String) = apply { body.addFallback(fallback) } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - putAllAdditionalBodyProperties(additionalBodyProperties) + fun frequencyPenalty(frequencyPenalty: Double?) = apply { + body.frequencyPenalty(frequencyPenalty) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - additionalBodyProperties.put(key, value) + /** + * Alias for [Builder.frequencyPenalty]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun frequencyPenalty(frequencyPenalty: Double) = + frequencyPenalty(frequencyPenalty as Double?) + + /** Alias for calling [Builder.frequencyPenalty] with `frequencyPenalty.orElse(null)`. */ + fun frequencyPenalty(frequencyPenalty: Optional) = + frequencyPenalty(frequencyPenalty.getOrNull()) + + /** + * Sets [Builder.frequencyPenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.frequencyPenalty] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun frequencyPenalty(frequencyPenalty: JsonField) = apply { + body.frequencyPenalty(frequencyPenalty) } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + fun functionCall(functionCall: FunctionCall?) = apply { body.functionCall(functionCall) } - fun removeAdditionalBodyProperty(key: String) = apply { - additionalBodyProperties.remove(key) + /** Alias for calling [Builder.functionCall] with `functionCall.orElse(null)`. */ + fun functionCall(functionCall: Optional) = + functionCall(functionCall.getOrNull()) + + /** + * Sets [Builder.functionCall] to an arbitrary JSON value. + * + * You should usually call [Builder.functionCall] with a well-typed [FunctionCall] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functionCall(functionCall: JsonField) = apply { + body.functionCall(functionCall) } - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalBodyProperty) + /** Alias for calling [functionCall] with `FunctionCall.ofString(string)`. */ + fun functionCall(string: String) = apply { body.functionCall(string) } + + /** Alias for calling [functionCall] with `FunctionCall.ofUnionMember1(unionMember1)`. */ + fun functionCall(unionMember1: FunctionCall.UnionMember1) = apply { + body.functionCall(unionMember1) } + fun functions(functions: List?) = apply { body.functions(functions) } + + /** Alias for calling [Builder.functions] with `functions.orElse(null)`. */ + fun functions(functions: Optional>) = functions(functions.getOrNull()) + /** - * Returns an immutable instance of [ChatCompleteParams]. + * Sets [Builder.functions] to an arbitrary JSON value. * - * Further updates to this [Builder] will not mutate the returned instance. + * You should usually call [Builder.functions] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functions(functions: JsonField>) = apply { body.functions(functions) } + + /** + * Adds a single [Function] to [functions]. * - * The following fields are required: - * ```java - * .model() - * ``` + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFunction(function: Function) = apply { body.addFunction(function) } + + fun guardrails(guardrails: List?) = apply { body.guardrails(guardrails) } + + /** Alias for calling [Builder.guardrails] with `guardrails.orElse(null)`. */ + fun guardrails(guardrails: Optional>) = guardrails(guardrails.getOrNull()) + + /** + * Sets [Builder.guardrails] to an arbitrary JSON value. * - * @throws IllegalStateException if any required field is unset. + * You should usually call [Builder.guardrails] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun build(): ChatCompleteParams = - ChatCompleteParams( - checkRequired("model", model), - additionalHeaders.build(), - additionalQueryParams.build(), - additionalBodyProperties.toImmutable(), - ) - } + fun guardrails(guardrails: JsonField>) = apply { body.guardrails(guardrails) } - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + /** + * Adds a single [String] to [guardrails]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addGuardrail(guardrail: String) = apply { body.addGuardrail(guardrail) } - fun _pathParam(index: Int): String = - when (index) { - 0 -> model - else -> "" - } + fun logitBias(logitBias: LogitBias?) = apply { body.logitBias(logitBias) } - override fun _headers(): Headers = additionalHeaders + /** Alias for calling [Builder.logitBias] with `logitBias.orElse(null)`. */ + fun logitBias(logitBias: Optional) = logitBias(logitBias.getOrNull()) - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Sets [Builder.logitBias] to an arbitrary JSON value. + * + * You should usually call [Builder.logitBias] with a well-typed [LogitBias] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun logitBias(logitBias: JsonField) = apply { body.logitBias(logitBias) } + + fun logprobs(logprobs: Boolean?) = apply { body.logprobs(logprobs) } + + /** + * Alias for [Builder.logprobs]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun logprobs(logprobs: Boolean) = logprobs(logprobs as Boolean?) + + /** Alias for calling [Builder.logprobs] with `logprobs.orElse(null)`. */ + fun logprobs(logprobs: Optional) = logprobs(logprobs.getOrNull()) + + /** + * Sets [Builder.logprobs] to an arbitrary JSON value. + * + * You should usually call [Builder.logprobs] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun logprobs(logprobs: JsonField) = apply { body.logprobs(logprobs) } + + fun maxTokens(maxTokens: Long?) = apply { body.maxTokens(maxTokens) } + + /** + * Alias for [Builder.maxTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxTokens(maxTokens: Long) = maxTokens(maxTokens as Long?) + + /** Alias for calling [Builder.maxTokens] with `maxTokens.orElse(null)`. */ + fun maxTokens(maxTokens: Optional) = maxTokens(maxTokens.getOrNull()) + + /** + * Sets [Builder.maxTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.maxTokens] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun maxTokens(maxTokens: JsonField) = apply { body.maxTokens(maxTokens) } + + fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } + + fun n(n: Long?) = apply { body.n(n) } + + /** + * Alias for [Builder.n]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun n(n: Long) = n(n as Long?) + + /** Alias for calling [Builder.n] with `n.orElse(null)`. */ + fun n(n: Optional) = n(n.getOrNull()) + + /** + * Sets [Builder.n] to an arbitrary JSON value. + * + * You should usually call [Builder.n] with a well-typed [Long] value instead. This method + * is primarily for setting the field to an undocumented or not yet supported value. + */ + fun n(n: JsonField) = apply { body.n(n) } + + fun numRetries(numRetries: Long?) = apply { body.numRetries(numRetries) } + + /** + * Alias for [Builder.numRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun numRetries(numRetries: Long) = numRetries(numRetries as Long?) + + /** Alias for calling [Builder.numRetries] with `numRetries.orElse(null)`. */ + fun numRetries(numRetries: Optional) = numRetries(numRetries.getOrNull()) + + /** + * Sets [Builder.numRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.numRetries] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun numRetries(numRetries: JsonField) = apply { body.numRetries(numRetries) } + + fun parallelToolCalls(parallelToolCalls: Boolean?) = apply { + body.parallelToolCalls(parallelToolCalls) + } + + /** + * Alias for [Builder.parallelToolCalls]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun parallelToolCalls(parallelToolCalls: Boolean) = + parallelToolCalls(parallelToolCalls as Boolean?) + + /** Alias for calling [Builder.parallelToolCalls] with `parallelToolCalls.orElse(null)`. */ + fun parallelToolCalls(parallelToolCalls: Optional) = + parallelToolCalls(parallelToolCalls.getOrNull()) + + /** + * Sets [Builder.parallelToolCalls] to an arbitrary JSON value. + * + * You should usually call [Builder.parallelToolCalls] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun parallelToolCalls(parallelToolCalls: JsonField) = apply { + body.parallelToolCalls(parallelToolCalls) + } + + fun presencePenalty(presencePenalty: Double?) = apply { + body.presencePenalty(presencePenalty) + } + + /** + * Alias for [Builder.presencePenalty]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun presencePenalty(presencePenalty: Double) = presencePenalty(presencePenalty as Double?) + + /** Alias for calling [Builder.presencePenalty] with `presencePenalty.orElse(null)`. */ + fun presencePenalty(presencePenalty: Optional) = + presencePenalty(presencePenalty.getOrNull()) + + /** + * Sets [Builder.presencePenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.presencePenalty] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun presencePenalty(presencePenalty: JsonField) = apply { + body.presencePenalty(presencePenalty) + } + + fun responseFormat(responseFormat: ResponseFormat?) = apply { + body.responseFormat(responseFormat) + } + + /** Alias for calling [Builder.responseFormat] with `responseFormat.orElse(null)`. */ + fun responseFormat(responseFormat: Optional) = + responseFormat(responseFormat.getOrNull()) + + /** + * Sets [Builder.responseFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.responseFormat] with a well-typed [ResponseFormat] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun responseFormat(responseFormat: JsonField) = apply { + body.responseFormat(responseFormat) + } + + fun seed(seed: Long?) = apply { body.seed(seed) } + + /** + * Alias for [Builder.seed]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun seed(seed: Long) = seed(seed as Long?) + + /** Alias for calling [Builder.seed] with `seed.orElse(null)`. */ + fun seed(seed: Optional) = seed(seed.getOrNull()) + + /** + * Sets [Builder.seed] to an arbitrary JSON value. + * + * You should usually call [Builder.seed] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun seed(seed: JsonField) = apply { body.seed(seed) } + + fun serviceTier(serviceTier: String?) = apply { body.serviceTier(serviceTier) } + + /** Alias for calling [Builder.serviceTier] with `serviceTier.orElse(null)`. */ + fun serviceTier(serviceTier: Optional) = serviceTier(serviceTier.getOrNull()) + + /** + * Sets [Builder.serviceTier] to an arbitrary JSON value. + * + * You should usually call [Builder.serviceTier] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun serviceTier(serviceTier: JsonField) = apply { body.serviceTier(serviceTier) } + + fun stop(stop: Stop?) = apply { body.stop(stop) } + + /** Alias for calling [Builder.stop] with `stop.orElse(null)`. */ + fun stop(stop: Optional) = stop(stop.getOrNull()) + + /** + * Sets [Builder.stop] to an arbitrary JSON value. + * + * You should usually call [Builder.stop] with a well-typed [Stop] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun stop(stop: JsonField) = apply { body.stop(stop) } + + /** Alias for calling [stop] with `Stop.ofString(string)`. */ + fun stop(string: String) = apply { body.stop(string) } + + /** Alias for calling [stop] with `Stop.ofStrings(strings)`. */ + fun stopOfStrings(strings: List) = apply { body.stopOfStrings(strings) } + + fun stream(stream: Boolean?) = apply { body.stream(stream) } + + /** + * Alias for [Builder.stream]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun stream(stream: Boolean) = stream(stream as Boolean?) + + /** Alias for calling [Builder.stream] with `stream.orElse(null)`. */ + fun stream(stream: Optional) = stream(stream.getOrNull()) + + /** + * Sets [Builder.stream] to an arbitrary JSON value. + * + * You should usually call [Builder.stream] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun stream(stream: JsonField) = apply { body.stream(stream) } + + fun streamOptions(streamOptions: StreamOptions?) = apply { + body.streamOptions(streamOptions) + } + + /** Alias for calling [Builder.streamOptions] with `streamOptions.orElse(null)`. */ + fun streamOptions(streamOptions: Optional) = + streamOptions(streamOptions.getOrNull()) + + /** + * Sets [Builder.streamOptions] to an arbitrary JSON value. + * + * You should usually call [Builder.streamOptions] with a well-typed [StreamOptions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun streamOptions(streamOptions: JsonField) = apply { + body.streamOptions(streamOptions) + } + + fun temperature(temperature: Double?) = apply { body.temperature(temperature) } + + /** + * Alias for [Builder.temperature]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun temperature(temperature: Double) = temperature(temperature as Double?) + + /** Alias for calling [Builder.temperature] with `temperature.orElse(null)`. */ + fun temperature(temperature: Optional) = temperature(temperature.getOrNull()) + + /** + * Sets [Builder.temperature] to an arbitrary JSON value. + * + * You should usually call [Builder.temperature] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun temperature(temperature: JsonField) = apply { body.temperature(temperature) } + + fun toolChoice(toolChoice: ToolChoice?) = apply { body.toolChoice(toolChoice) } + + /** Alias for calling [Builder.toolChoice] with `toolChoice.orElse(null)`. */ + fun toolChoice(toolChoice: Optional) = toolChoice(toolChoice.getOrNull()) + + /** + * Sets [Builder.toolChoice] to an arbitrary JSON value. + * + * You should usually call [Builder.toolChoice] with a well-typed [ToolChoice] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun toolChoice(toolChoice: JsonField) = apply { body.toolChoice(toolChoice) } + + /** Alias for calling [toolChoice] with `ToolChoice.ofString(string)`. */ + fun toolChoice(string: String) = apply { body.toolChoice(string) } + + /** Alias for calling [toolChoice] with `ToolChoice.ofUnionMember1(unionMember1)`. */ + fun toolChoice(unionMember1: ToolChoice.UnionMember1) = apply { + body.toolChoice(unionMember1) + } + + fun tools(tools: List?) = apply { body.tools(tools) } + + /** Alias for calling [Builder.tools] with `tools.orElse(null)`. */ + fun tools(tools: Optional>) = tools(tools.getOrNull()) + + /** + * Sets [Builder.tools] to an arbitrary JSON value. + * + * You should usually call [Builder.tools] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tools(tools: JsonField>) = apply { body.tools(tools) } + + /** + * Adds a single [Tool] to [tools]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTool(tool: Tool) = apply { body.addTool(tool) } + + fun topLogprobs(topLogprobs: Long?) = apply { body.topLogprobs(topLogprobs) } + + /** + * Alias for [Builder.topLogprobs]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun topLogprobs(topLogprobs: Long) = topLogprobs(topLogprobs as Long?) + + /** Alias for calling [Builder.topLogprobs] with `topLogprobs.orElse(null)`. */ + fun topLogprobs(topLogprobs: Optional) = topLogprobs(topLogprobs.getOrNull()) + + /** + * Sets [Builder.topLogprobs] to an arbitrary JSON value. + * + * You should usually call [Builder.topLogprobs] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun topLogprobs(topLogprobs: JsonField) = apply { body.topLogprobs(topLogprobs) } + + fun topP(topP: Double?) = apply { body.topP(topP) } + + /** + * Alias for [Builder.topP]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun topP(topP: Double) = topP(topP as Double?) + + /** Alias for calling [Builder.topP] with `topP.orElse(null)`. */ + fun topP(topP: Optional) = topP(topP.getOrNull()) + + /** + * Sets [Builder.topP] to an arbitrary JSON value. + * + * You should usually call [Builder.topP] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun topP(topP: JsonField) = apply { body.topP(topP) } + + fun user(user: String?) = apply { body.user(user) } + + /** Alias for calling [Builder.user] with `user.orElse(null)`. */ + fun user(user: Optional) = user(user.getOrNull()) + + /** + * Sets [Builder.user] to an arbitrary JSON value. + * + * You should usually call [Builder.user] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun user(user: JsonField) = apply { body.user(user) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [ChatCompleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .messages() + * .bodyModel() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompleteParams = + ChatCompleteParams( + pathModel, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> pathModel ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val messages: JsonField>, + private val bodyModel: JsonField, + private val caching: JsonField, + private val contextWindowFallbackDict: JsonField, + private val fallbacks: JsonField>, + private val frequencyPenalty: JsonField, + private val functionCall: JsonField, + private val functions: JsonField>, + private val guardrails: JsonField>, + private val logitBias: JsonField, + private val logprobs: JsonField, + private val maxTokens: JsonField, + private val metadata: JsonField, + private val n: JsonField, + private val numRetries: JsonField, + private val parallelToolCalls: JsonField, + private val presencePenalty: JsonField, + private val responseFormat: JsonField, + private val seed: JsonField, + private val serviceTier: JsonField, + private val stop: JsonField, + private val stream: JsonField, + private val streamOptions: JsonField, + private val temperature: JsonField, + private val toolChoice: JsonField, + private val tools: JsonField>, + private val topLogprobs: JsonField, + private val topP: JsonField, + private val user: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("messages") + @ExcludeMissing + messages: JsonField> = JsonMissing.of(), + @JsonProperty("model") @ExcludeMissing bodyModel: JsonField = JsonMissing.of(), + @JsonProperty("caching") @ExcludeMissing caching: JsonField = JsonMissing.of(), + @JsonProperty("context_window_fallback_dict") + @ExcludeMissing + contextWindowFallbackDict: JsonField = JsonMissing.of(), + @JsonProperty("fallbacks") + @ExcludeMissing + fallbacks: JsonField> = JsonMissing.of(), + @JsonProperty("frequency_penalty") + @ExcludeMissing + frequencyPenalty: JsonField = JsonMissing.of(), + @JsonProperty("function_call") + @ExcludeMissing + functionCall: JsonField = JsonMissing.of(), + @JsonProperty("functions") + @ExcludeMissing + functions: JsonField> = JsonMissing.of(), + @JsonProperty("guardrails") + @ExcludeMissing + guardrails: JsonField> = JsonMissing.of(), + @JsonProperty("logit_bias") + @ExcludeMissing + logitBias: JsonField = JsonMissing.of(), + @JsonProperty("logprobs") + @ExcludeMissing + logprobs: JsonField = JsonMissing.of(), + @JsonProperty("max_tokens") + @ExcludeMissing + maxTokens: JsonField = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("n") @ExcludeMissing n: JsonField = JsonMissing.of(), + @JsonProperty("num_retries") + @ExcludeMissing + numRetries: JsonField = JsonMissing.of(), + @JsonProperty("parallel_tool_calls") + @ExcludeMissing + parallelToolCalls: JsonField = JsonMissing.of(), + @JsonProperty("presence_penalty") + @ExcludeMissing + presencePenalty: JsonField = JsonMissing.of(), + @JsonProperty("response_format") + @ExcludeMissing + responseFormat: JsonField = JsonMissing.of(), + @JsonProperty("seed") @ExcludeMissing seed: JsonField = JsonMissing.of(), + @JsonProperty("service_tier") + @ExcludeMissing + serviceTier: JsonField = JsonMissing.of(), + @JsonProperty("stop") @ExcludeMissing stop: JsonField = JsonMissing.of(), + @JsonProperty("stream") @ExcludeMissing stream: JsonField = JsonMissing.of(), + @JsonProperty("stream_options") + @ExcludeMissing + streamOptions: JsonField = JsonMissing.of(), + @JsonProperty("temperature") + @ExcludeMissing + temperature: JsonField = JsonMissing.of(), + @JsonProperty("tool_choice") + @ExcludeMissing + toolChoice: JsonField = JsonMissing.of(), + @JsonProperty("tools") @ExcludeMissing tools: JsonField> = JsonMissing.of(), + @JsonProperty("top_logprobs") + @ExcludeMissing + topLogprobs: JsonField = JsonMissing.of(), + @JsonProperty("top_p") @ExcludeMissing topP: JsonField = JsonMissing.of(), + @JsonProperty("user") @ExcludeMissing user: JsonField = JsonMissing.of(), + ) : this( + messages, + bodyModel, + caching, + contextWindowFallbackDict, + fallbacks, + frequencyPenalty, + functionCall, + functions, + guardrails, + logitBias, + logprobs, + maxTokens, + metadata, + n, + numRetries, + parallelToolCalls, + presencePenalty, + responseFormat, + seed, + serviceTier, + stop, + stream, + streamOptions, + temperature, + toolChoice, + tools, + topLogprobs, + topP, + user, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun messages(): List = messages.getRequired("messages") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun bodyModel(): String = bodyModel.getRequired("model") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun caching(): Optional = caching.getOptional("caching") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun contextWindowFallbackDict(): Optional = + contextWindowFallbackDict.getOptional("context_window_fallback_dict") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fallbacks(): Optional> = fallbacks.getOptional("fallbacks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun frequencyPenalty(): Optional = frequencyPenalty.getOptional("frequency_penalty") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functionCall(): Optional = functionCall.getOptional("function_call") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functions(): Optional> = functions.getOptional("functions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun guardrails(): Optional> = guardrails.getOptional("guardrails") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logitBias(): Optional = logitBias.getOptional("logit_bias") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logprobs(): Optional = logprobs.getOptional("logprobs") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxTokens(): Optional = maxTokens.getOptional("max_tokens") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun n(): Optional = n.getOptional("n") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun numRetries(): Optional = numRetries.getOptional("num_retries") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun parallelToolCalls(): Optional = + parallelToolCalls.getOptional("parallel_tool_calls") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun presencePenalty(): Optional = presencePenalty.getOptional("presence_penalty") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun responseFormat(): Optional = + responseFormat.getOptional("response_format") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun seed(): Optional = seed.getOptional("seed") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun serviceTier(): Optional = serviceTier.getOptional("service_tier") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stop(): Optional = stop.getOptional("stop") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stream(): Optional = stream.getOptional("stream") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun streamOptions(): Optional = streamOptions.getOptional("stream_options") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun temperature(): Optional = temperature.getOptional("temperature") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolChoice(): Optional = toolChoice.getOptional("tool_choice") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tools(): Optional> = tools.getOptional("tools") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun topLogprobs(): Optional = topLogprobs.getOptional("top_logprobs") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun topP(): Optional = topP.getOptional("top_p") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun user(): Optional = user.getOptional("user") + + /** + * Returns the raw JSON value of [messages]. + * + * Unlike [messages], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("messages") + @ExcludeMissing + fun _messages(): JsonField> = messages + + /** + * Returns the raw JSON value of [bodyModel]. + * + * Unlike [bodyModel], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _bodyModel(): JsonField = bodyModel + + /** + * Returns the raw JSON value of [caching]. + * + * Unlike [caching], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("caching") @ExcludeMissing fun _caching(): JsonField = caching + + /** + * Returns the raw JSON value of [contextWindowFallbackDict]. + * + * Unlike [contextWindowFallbackDict], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("context_window_fallback_dict") + @ExcludeMissing + fun _contextWindowFallbackDict(): JsonField = + contextWindowFallbackDict + + /** + * Returns the raw JSON value of [fallbacks]. + * + * Unlike [fallbacks], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fallbacks") + @ExcludeMissing + fun _fallbacks(): JsonField> = fallbacks + + /** + * Returns the raw JSON value of [frequencyPenalty]. + * + * Unlike [frequencyPenalty], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("frequency_penalty") + @ExcludeMissing + fun _frequencyPenalty(): JsonField = frequencyPenalty + + /** + * Returns the raw JSON value of [functionCall]. + * + * Unlike [functionCall], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_call") + @ExcludeMissing + fun _functionCall(): JsonField = functionCall + + /** + * Returns the raw JSON value of [functions]. + * + * Unlike [functions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("functions") + @ExcludeMissing + fun _functions(): JsonField> = functions + + /** + * Returns the raw JSON value of [guardrails]. + * + * Unlike [guardrails], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("guardrails") + @ExcludeMissing + fun _guardrails(): JsonField> = guardrails + + /** + * Returns the raw JSON value of [logitBias]. + * + * Unlike [logitBias], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("logit_bias") + @ExcludeMissing + fun _logitBias(): JsonField = logitBias + + /** + * Returns the raw JSON value of [logprobs]. + * + * Unlike [logprobs], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("logprobs") @ExcludeMissing fun _logprobs(): JsonField = logprobs + + /** + * Returns the raw JSON value of [maxTokens]. + * + * Unlike [maxTokens], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("max_tokens") @ExcludeMissing fun _maxTokens(): JsonField = maxTokens + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [n]. + * + * Unlike [n], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("n") @ExcludeMissing fun _n(): JsonField = n + + /** + * Returns the raw JSON value of [numRetries]. + * + * Unlike [numRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("num_retries") @ExcludeMissing fun _numRetries(): JsonField = numRetries + + /** + * Returns the raw JSON value of [parallelToolCalls]. + * + * Unlike [parallelToolCalls], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("parallel_tool_calls") + @ExcludeMissing + fun _parallelToolCalls(): JsonField = parallelToolCalls + + /** + * Returns the raw JSON value of [presencePenalty]. + * + * Unlike [presencePenalty], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("presence_penalty") + @ExcludeMissing + fun _presencePenalty(): JsonField = presencePenalty + + /** + * Returns the raw JSON value of [responseFormat]. + * + * Unlike [responseFormat], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_format") + @ExcludeMissing + fun _responseFormat(): JsonField = responseFormat + + /** + * Returns the raw JSON value of [seed]. + * + * Unlike [seed], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("seed") @ExcludeMissing fun _seed(): JsonField = seed + + /** + * Returns the raw JSON value of [serviceTier]. + * + * Unlike [serviceTier], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("service_tier") + @ExcludeMissing + fun _serviceTier(): JsonField = serviceTier + + /** + * Returns the raw JSON value of [stop]. + * + * Unlike [stop], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("stop") @ExcludeMissing fun _stop(): JsonField = stop + + /** + * Returns the raw JSON value of [stream]. + * + * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("stream") @ExcludeMissing fun _stream(): JsonField = stream + + /** + * Returns the raw JSON value of [streamOptions]. + * + * Unlike [streamOptions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("stream_options") + @ExcludeMissing + fun _streamOptions(): JsonField = streamOptions + + /** + * Returns the raw JSON value of [temperature]. + * + * Unlike [temperature], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("temperature") + @ExcludeMissing + fun _temperature(): JsonField = temperature + + /** + * Returns the raw JSON value of [toolChoice]. + * + * Unlike [toolChoice], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_choice") + @ExcludeMissing + fun _toolChoice(): JsonField = toolChoice + + /** + * Returns the raw JSON value of [tools]. + * + * Unlike [tools], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonField> = tools + + /** + * Returns the raw JSON value of [topLogprobs]. + * + * Unlike [topLogprobs], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("top_logprobs") + @ExcludeMissing + fun _topLogprobs(): JsonField = topLogprobs + + /** + * Returns the raw JSON value of [topP]. + * + * Unlike [topP], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("top_p") @ExcludeMissing fun _topP(): JsonField = topP + + /** + * Returns the raw JSON value of [user]. + * + * Unlike [user], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user") @ExcludeMissing fun _user(): JsonField = user + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .messages() + * .bodyModel() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var messages: JsonField>? = null + private var bodyModel: JsonField? = null + private var caching: JsonField = JsonMissing.of() + private var contextWindowFallbackDict: JsonField = + JsonMissing.of() + private var fallbacks: JsonField>? = null + private var frequencyPenalty: JsonField = JsonMissing.of() + private var functionCall: JsonField = JsonMissing.of() + private var functions: JsonField>? = null + private var guardrails: JsonField>? = null + private var logitBias: JsonField = JsonMissing.of() + private var logprobs: JsonField = JsonMissing.of() + private var maxTokens: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var n: JsonField = JsonMissing.of() + private var numRetries: JsonField = JsonMissing.of() + private var parallelToolCalls: JsonField = JsonMissing.of() + private var presencePenalty: JsonField = JsonMissing.of() + private var responseFormat: JsonField = JsonMissing.of() + private var seed: JsonField = JsonMissing.of() + private var serviceTier: JsonField = JsonMissing.of() + private var stop: JsonField = JsonMissing.of() + private var stream: JsonField = JsonMissing.of() + private var streamOptions: JsonField = JsonMissing.of() + private var temperature: JsonField = JsonMissing.of() + private var toolChoice: JsonField = JsonMissing.of() + private var tools: JsonField>? = null + private var topLogprobs: JsonField = JsonMissing.of() + private var topP: JsonField = JsonMissing.of() + private var user: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + messages = body.messages.map { it.toMutableList() } + bodyModel = body.bodyModel + caching = body.caching + contextWindowFallbackDict = body.contextWindowFallbackDict + fallbacks = body.fallbacks.map { it.toMutableList() } + frequencyPenalty = body.frequencyPenalty + functionCall = body.functionCall + functions = body.functions.map { it.toMutableList() } + guardrails = body.guardrails.map { it.toMutableList() } + logitBias = body.logitBias + logprobs = body.logprobs + maxTokens = body.maxTokens + metadata = body.metadata + n = body.n + numRetries = body.numRetries + parallelToolCalls = body.parallelToolCalls + presencePenalty = body.presencePenalty + responseFormat = body.responseFormat + seed = body.seed + serviceTier = body.serviceTier + stop = body.stop + stream = body.stream + streamOptions = body.streamOptions + temperature = body.temperature + toolChoice = body.toolChoice + tools = body.tools.map { it.toMutableList() } + topLogprobs = body.topLogprobs + topP = body.topP + user = body.user + additionalProperties = body.additionalProperties.toMutableMap() + } + + fun messages(messages: List) = messages(JsonField.of(messages)) + + /** + * Sets [Builder.messages] to an arbitrary JSON value. + * + * You should usually call [Builder.messages] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun messages(messages: JsonField>) = apply { + this.messages = messages.map { it.toMutableList() } + } + + /** + * Adds a single [Message] to [messages]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMessage(message: Message) = apply { + messages = + (messages ?: JsonField.of(mutableListOf())).also { + checkKnown("messages", it).add(message) + } + } + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionUser(chatCompletionUser)`. + */ + fun addMessage(chatCompletionUser: Message.ChatCompletionUserMessage) = + addMessage(Message.ofChatCompletionUser(chatCompletionUser)) + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionAssistant(chatCompletionAssistant)`. + */ + fun addMessage(chatCompletionAssistant: Message.ChatCompletionAssistantMessage) = + addMessage(Message.ofChatCompletionAssistant(chatCompletionAssistant)) + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionTool(chatCompletionTool)`. + */ + fun addMessage(chatCompletionTool: Message.ChatCompletionToolMessage) = + addMessage(Message.ofChatCompletionTool(chatCompletionTool)) + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionSystem(chatCompletionSystem)`. + */ + fun addMessage(chatCompletionSystem: Message.ChatCompletionSystemMessage) = + addMessage(Message.ofChatCompletionSystem(chatCompletionSystem)) + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionFunction(chatCompletionFunction)`. + */ + fun addMessage(chatCompletionFunction: Message.ChatCompletionFunctionMessage) = + addMessage(Message.ofChatCompletionFunction(chatCompletionFunction)) + + /** + * Alias for calling [addMessage] with + * `Message.ofChatCompletionDeveloper(chatCompletionDeveloper)`. + */ + fun addMessage(chatCompletionDeveloper: Message.ChatCompletionDeveloperMessage) = + addMessage(Message.ofChatCompletionDeveloper(chatCompletionDeveloper)) + + fun bodyModel(bodyModel: String) = bodyModel(JsonField.of(bodyModel)) + + /** + * Sets [Builder.bodyModel] to an arbitrary JSON value. + * + * You should usually call [Builder.bodyModel] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun bodyModel(bodyModel: JsonField) = apply { this.bodyModel = bodyModel } + + fun caching(caching: Boolean?) = caching(JsonField.ofNullable(caching)) + + /** + * Alias for [Builder.caching]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun caching(caching: Boolean) = caching(caching as Boolean?) + + /** Alias for calling [Builder.caching] with `caching.orElse(null)`. */ + fun caching(caching: Optional) = caching(caching.getOrNull()) + + /** + * Sets [Builder.caching] to an arbitrary JSON value. + * + * You should usually call [Builder.caching] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun caching(caching: JsonField) = apply { this.caching = caching } + + fun contextWindowFallbackDict(contextWindowFallbackDict: ContextWindowFallbackDict?) = + contextWindowFallbackDict(JsonField.ofNullable(contextWindowFallbackDict)) + + /** + * Alias for calling [Builder.contextWindowFallbackDict] with + * `contextWindowFallbackDict.orElse(null)`. + */ + fun contextWindowFallbackDict( + contextWindowFallbackDict: Optional + ) = contextWindowFallbackDict(contextWindowFallbackDict.getOrNull()) + + /** + * Sets [Builder.contextWindowFallbackDict] to an arbitrary JSON value. + * + * You should usually call [Builder.contextWindowFallbackDict] with a well-typed + * [ContextWindowFallbackDict] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun contextWindowFallbackDict( + contextWindowFallbackDict: JsonField + ) = apply { this.contextWindowFallbackDict = contextWindowFallbackDict } + + fun fallbacks(fallbacks: List?) = fallbacks(JsonField.ofNullable(fallbacks)) + + /** Alias for calling [Builder.fallbacks] with `fallbacks.orElse(null)`. */ + fun fallbacks(fallbacks: Optional>) = fallbacks(fallbacks.getOrNull()) + + /** + * Sets [Builder.fallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.fallbacks] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fallbacks(fallbacks: JsonField>) = apply { + this.fallbacks = fallbacks.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [fallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFallback(fallback: String) = apply { + fallbacks = + (fallbacks ?: JsonField.of(mutableListOf())).also { + checkKnown("fallbacks", it).add(fallback) + } + } + + fun frequencyPenalty(frequencyPenalty: Double?) = + frequencyPenalty(JsonField.ofNullable(frequencyPenalty)) + + /** + * Alias for [Builder.frequencyPenalty]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun frequencyPenalty(frequencyPenalty: Double) = + frequencyPenalty(frequencyPenalty as Double?) + + /** + * Alias for calling [Builder.frequencyPenalty] with `frequencyPenalty.orElse(null)`. + */ + fun frequencyPenalty(frequencyPenalty: Optional) = + frequencyPenalty(frequencyPenalty.getOrNull()) + + /** + * Sets [Builder.frequencyPenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.frequencyPenalty] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun frequencyPenalty(frequencyPenalty: JsonField) = apply { + this.frequencyPenalty = frequencyPenalty + } + + fun functionCall(functionCall: FunctionCall?) = + functionCall(JsonField.ofNullable(functionCall)) + + /** Alias for calling [Builder.functionCall] with `functionCall.orElse(null)`. */ + fun functionCall(functionCall: Optional) = + functionCall(functionCall.getOrNull()) + + /** + * Sets [Builder.functionCall] to an arbitrary JSON value. + * + * You should usually call [Builder.functionCall] with a well-typed [FunctionCall] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functionCall(functionCall: JsonField) = apply { + this.functionCall = functionCall + } + + /** Alias for calling [functionCall] with `FunctionCall.ofString(string)`. */ + fun functionCall(string: String) = functionCall(FunctionCall.ofString(string)) + + /** + * Alias for calling [functionCall] with `FunctionCall.ofUnionMember1(unionMember1)`. + */ + fun functionCall(unionMember1: FunctionCall.UnionMember1) = + functionCall(FunctionCall.ofUnionMember1(unionMember1)) + + fun functions(functions: List?) = functions(JsonField.ofNullable(functions)) + + /** Alias for calling [Builder.functions] with `functions.orElse(null)`. */ + fun functions(functions: Optional>) = functions(functions.getOrNull()) + + /** + * Sets [Builder.functions] to an arbitrary JSON value. + * + * You should usually call [Builder.functions] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun functions(functions: JsonField>) = apply { + this.functions = functions.map { it.toMutableList() } + } + + /** + * Adds a single [Function] to [functions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFunction(function: Function) = apply { + functions = + (functions ?: JsonField.of(mutableListOf())).also { + checkKnown("functions", it).add(function) + } + } + + fun guardrails(guardrails: List?) = guardrails(JsonField.ofNullable(guardrails)) + + /** Alias for calling [Builder.guardrails] with `guardrails.orElse(null)`. */ + fun guardrails(guardrails: Optional>) = guardrails(guardrails.getOrNull()) + + /** + * Sets [Builder.guardrails] to an arbitrary JSON value. + * + * You should usually call [Builder.guardrails] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun guardrails(guardrails: JsonField>) = apply { + this.guardrails = guardrails.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [guardrails]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addGuardrail(guardrail: String) = apply { + guardrails = + (guardrails ?: JsonField.of(mutableListOf())).also { + checkKnown("guardrails", it).add(guardrail) + } + } + + fun logitBias(logitBias: LogitBias?) = logitBias(JsonField.ofNullable(logitBias)) + + /** Alias for calling [Builder.logitBias] with `logitBias.orElse(null)`. */ + fun logitBias(logitBias: Optional) = logitBias(logitBias.getOrNull()) + + /** + * Sets [Builder.logitBias] to an arbitrary JSON value. + * + * You should usually call [Builder.logitBias] with a well-typed [LogitBias] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun logitBias(logitBias: JsonField) = apply { this.logitBias = logitBias } + + fun logprobs(logprobs: Boolean?) = logprobs(JsonField.ofNullable(logprobs)) + + /** + * Alias for [Builder.logprobs]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun logprobs(logprobs: Boolean) = logprobs(logprobs as Boolean?) + + /** Alias for calling [Builder.logprobs] with `logprobs.orElse(null)`. */ + fun logprobs(logprobs: Optional) = logprobs(logprobs.getOrNull()) + + /** + * Sets [Builder.logprobs] to an arbitrary JSON value. + * + * You should usually call [Builder.logprobs] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun logprobs(logprobs: JsonField) = apply { this.logprobs = logprobs } + + fun maxTokens(maxTokens: Long?) = maxTokens(JsonField.ofNullable(maxTokens)) + + /** + * Alias for [Builder.maxTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxTokens(maxTokens: Long) = maxTokens(maxTokens as Long?) + + /** Alias for calling [Builder.maxTokens] with `maxTokens.orElse(null)`. */ + fun maxTokens(maxTokens: Optional) = maxTokens(maxTokens.getOrNull()) + + /** + * Sets [Builder.maxTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.maxTokens] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxTokens(maxTokens: JsonField) = apply { this.maxTokens = maxTokens } + + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun n(n: Long?) = n(JsonField.ofNullable(n)) + + /** + * Alias for [Builder.n]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun n(n: Long) = n(n as Long?) + + /** Alias for calling [Builder.n] with `n.orElse(null)`. */ + fun n(n: Optional) = n(n.getOrNull()) + + /** + * Sets [Builder.n] to an arbitrary JSON value. + * + * You should usually call [Builder.n] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun n(n: JsonField) = apply { this.n = n } + + fun numRetries(numRetries: Long?) = numRetries(JsonField.ofNullable(numRetries)) + + /** + * Alias for [Builder.numRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun numRetries(numRetries: Long) = numRetries(numRetries as Long?) + + /** Alias for calling [Builder.numRetries] with `numRetries.orElse(null)`. */ + fun numRetries(numRetries: Optional) = numRetries(numRetries.getOrNull()) + + /** + * Sets [Builder.numRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.numRetries] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun numRetries(numRetries: JsonField) = apply { this.numRetries = numRetries } + + fun parallelToolCalls(parallelToolCalls: Boolean?) = + parallelToolCalls(JsonField.ofNullable(parallelToolCalls)) + + /** + * Alias for [Builder.parallelToolCalls]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun parallelToolCalls(parallelToolCalls: Boolean) = + parallelToolCalls(parallelToolCalls as Boolean?) + + /** + * Alias for calling [Builder.parallelToolCalls] with `parallelToolCalls.orElse(null)`. + */ + fun parallelToolCalls(parallelToolCalls: Optional) = + parallelToolCalls(parallelToolCalls.getOrNull()) + + /** + * Sets [Builder.parallelToolCalls] to an arbitrary JSON value. + * + * You should usually call [Builder.parallelToolCalls] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun parallelToolCalls(parallelToolCalls: JsonField) = apply { + this.parallelToolCalls = parallelToolCalls + } + + fun presencePenalty(presencePenalty: Double?) = + presencePenalty(JsonField.ofNullable(presencePenalty)) + + /** + * Alias for [Builder.presencePenalty]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun presencePenalty(presencePenalty: Double) = + presencePenalty(presencePenalty as Double?) + + /** Alias for calling [Builder.presencePenalty] with `presencePenalty.orElse(null)`. */ + fun presencePenalty(presencePenalty: Optional) = + presencePenalty(presencePenalty.getOrNull()) + + /** + * Sets [Builder.presencePenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.presencePenalty] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun presencePenalty(presencePenalty: JsonField) = apply { + this.presencePenalty = presencePenalty + } + + fun responseFormat(responseFormat: ResponseFormat?) = + responseFormat(JsonField.ofNullable(responseFormat)) + + /** Alias for calling [Builder.responseFormat] with `responseFormat.orElse(null)`. */ + fun responseFormat(responseFormat: Optional) = + responseFormat(responseFormat.getOrNull()) + + /** + * Sets [Builder.responseFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.responseFormat] with a well-typed [ResponseFormat] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun responseFormat(responseFormat: JsonField) = apply { + this.responseFormat = responseFormat + } + + fun seed(seed: Long?) = seed(JsonField.ofNullable(seed)) + + /** + * Alias for [Builder.seed]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun seed(seed: Long) = seed(seed as Long?) + + /** Alias for calling [Builder.seed] with `seed.orElse(null)`. */ + fun seed(seed: Optional) = seed(seed.getOrNull()) + + /** + * Sets [Builder.seed] to an arbitrary JSON value. + * + * You should usually call [Builder.seed] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun seed(seed: JsonField) = apply { this.seed = seed } + + fun serviceTier(serviceTier: String?) = serviceTier(JsonField.ofNullable(serviceTier)) + + /** Alias for calling [Builder.serviceTier] with `serviceTier.orElse(null)`. */ + fun serviceTier(serviceTier: Optional) = serviceTier(serviceTier.getOrNull()) + + /** + * Sets [Builder.serviceTier] to an arbitrary JSON value. + * + * You should usually call [Builder.serviceTier] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun serviceTier(serviceTier: JsonField) = apply { + this.serviceTier = serviceTier + } + + fun stop(stop: Stop?) = stop(JsonField.ofNullable(stop)) + + /** Alias for calling [Builder.stop] with `stop.orElse(null)`. */ + fun stop(stop: Optional) = stop(stop.getOrNull()) + + /** + * Sets [Builder.stop] to an arbitrary JSON value. + * + * You should usually call [Builder.stop] with a well-typed [Stop] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun stop(stop: JsonField) = apply { this.stop = stop } + + /** Alias for calling [stop] with `Stop.ofString(string)`. */ + fun stop(string: String) = stop(Stop.ofString(string)) + + /** Alias for calling [stop] with `Stop.ofStrings(strings)`. */ + fun stopOfStrings(strings: List) = stop(Stop.ofStrings(strings)) + + fun stream(stream: Boolean?) = stream(JsonField.ofNullable(stream)) + + /** + * Alias for [Builder.stream]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun stream(stream: Boolean) = stream(stream as Boolean?) + + /** Alias for calling [Builder.stream] with `stream.orElse(null)`. */ + fun stream(stream: Optional) = stream(stream.getOrNull()) + + /** + * Sets [Builder.stream] to an arbitrary JSON value. + * + * You should usually call [Builder.stream] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun stream(stream: JsonField) = apply { this.stream = stream } + + fun streamOptions(streamOptions: StreamOptions?) = + streamOptions(JsonField.ofNullable(streamOptions)) + + /** Alias for calling [Builder.streamOptions] with `streamOptions.orElse(null)`. */ + fun streamOptions(streamOptions: Optional) = + streamOptions(streamOptions.getOrNull()) + + /** + * Sets [Builder.streamOptions] to an arbitrary JSON value. + * + * You should usually call [Builder.streamOptions] with a well-typed [StreamOptions] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun streamOptions(streamOptions: JsonField) = apply { + this.streamOptions = streamOptions + } + + fun temperature(temperature: Double?) = temperature(JsonField.ofNullable(temperature)) + + /** + * Alias for [Builder.temperature]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun temperature(temperature: Double) = temperature(temperature as Double?) + + /** Alias for calling [Builder.temperature] with `temperature.orElse(null)`. */ + fun temperature(temperature: Optional) = temperature(temperature.getOrNull()) + + /** + * Sets [Builder.temperature] to an arbitrary JSON value. + * + * You should usually call [Builder.temperature] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun temperature(temperature: JsonField) = apply { + this.temperature = temperature + } + + fun toolChoice(toolChoice: ToolChoice?) = toolChoice(JsonField.ofNullable(toolChoice)) + + /** Alias for calling [Builder.toolChoice] with `toolChoice.orElse(null)`. */ + fun toolChoice(toolChoice: Optional) = toolChoice(toolChoice.getOrNull()) + + /** + * Sets [Builder.toolChoice] to an arbitrary JSON value. + * + * You should usually call [Builder.toolChoice] with a well-typed [ToolChoice] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun toolChoice(toolChoice: JsonField) = apply { + this.toolChoice = toolChoice + } + + /** Alias for calling [toolChoice] with `ToolChoice.ofString(string)`. */ + fun toolChoice(string: String) = toolChoice(ToolChoice.ofString(string)) + + /** Alias for calling [toolChoice] with `ToolChoice.ofUnionMember1(unionMember1)`. */ + fun toolChoice(unionMember1: ToolChoice.UnionMember1) = + toolChoice(ToolChoice.ofUnionMember1(unionMember1)) + + fun tools(tools: List?) = tools(JsonField.ofNullable(tools)) + + /** Alias for calling [Builder.tools] with `tools.orElse(null)`. */ + fun tools(tools: Optional>) = tools(tools.getOrNull()) + + /** + * Sets [Builder.tools] to an arbitrary JSON value. + * + * You should usually call [Builder.tools] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tools(tools: JsonField>) = apply { + this.tools = tools.map { it.toMutableList() } + } + + /** + * Adds a single [Tool] to [tools]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTool(tool: Tool) = apply { + tools = + (tools ?: JsonField.of(mutableListOf())).also { + checkKnown("tools", it).add(tool) + } + } + + fun topLogprobs(topLogprobs: Long?) = topLogprobs(JsonField.ofNullable(topLogprobs)) + + /** + * Alias for [Builder.topLogprobs]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun topLogprobs(topLogprobs: Long) = topLogprobs(topLogprobs as Long?) + + /** Alias for calling [Builder.topLogprobs] with `topLogprobs.orElse(null)`. */ + fun topLogprobs(topLogprobs: Optional) = topLogprobs(topLogprobs.getOrNull()) + + /** + * Sets [Builder.topLogprobs] to an arbitrary JSON value. + * + * You should usually call [Builder.topLogprobs] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun topLogprobs(topLogprobs: JsonField) = apply { this.topLogprobs = topLogprobs } + + fun topP(topP: Double?) = topP(JsonField.ofNullable(topP)) + + /** + * Alias for [Builder.topP]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun topP(topP: Double) = topP(topP as Double?) + + /** Alias for calling [Builder.topP] with `topP.orElse(null)`. */ + fun topP(topP: Optional) = topP(topP.getOrNull()) + + /** + * Sets [Builder.topP] to an arbitrary JSON value. + * + * You should usually call [Builder.topP] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun topP(topP: JsonField) = apply { this.topP = topP } + + fun user(user: String?) = user(JsonField.ofNullable(user)) + + /** Alias for calling [Builder.user] with `user.orElse(null)`. */ + fun user(user: Optional) = user(user.getOrNull()) + + /** + * Sets [Builder.user] to an arbitrary JSON value. + * + * You should usually call [Builder.user] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun user(user: JsonField) = apply { this.user = user } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .messages() + * .bodyModel() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("messages", messages).map { it.toImmutable() }, + checkRequired("bodyModel", bodyModel), + caching, + contextWindowFallbackDict, + (fallbacks ?: JsonMissing.of()).map { it.toImmutable() }, + frequencyPenalty, + functionCall, + (functions ?: JsonMissing.of()).map { it.toImmutable() }, + (guardrails ?: JsonMissing.of()).map { it.toImmutable() }, + logitBias, + logprobs, + maxTokens, + metadata, + n, + numRetries, + parallelToolCalls, + presencePenalty, + responseFormat, + seed, + serviceTier, + stop, + stream, + streamOptions, + temperature, + toolChoice, + (tools ?: JsonMissing.of()).map { it.toImmutable() }, + topLogprobs, + topP, + user, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + messages().forEach { it.validate() } + bodyModel() + caching() + contextWindowFallbackDict().ifPresent { it.validate() } + fallbacks() + frequencyPenalty() + functionCall().ifPresent { it.validate() } + functions().ifPresent { it.forEach { it.validate() } } + guardrails() + logitBias().ifPresent { it.validate() } + logprobs() + maxTokens() + metadata().ifPresent { it.validate() } + n() + numRetries() + parallelToolCalls() + presencePenalty() + responseFormat().ifPresent { it.validate() } + seed() + serviceTier() + stop().ifPresent { it.validate() } + stream() + streamOptions().ifPresent { it.validate() } + temperature() + toolChoice().ifPresent { it.validate() } + tools().ifPresent { it.forEach { it.validate() } } + topLogprobs() + topP() + user() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (messages.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (bodyModel.asKnown().isPresent) 1 else 0) + + (if (caching.asKnown().isPresent) 1 else 0) + + (contextWindowFallbackDict.asKnown().getOrNull()?.validity() ?: 0) + + (fallbacks.asKnown().getOrNull()?.size ?: 0) + + (if (frequencyPenalty.asKnown().isPresent) 1 else 0) + + (functionCall.asKnown().getOrNull()?.validity() ?: 0) + + (functions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (guardrails.asKnown().getOrNull()?.size ?: 0) + + (logitBias.asKnown().getOrNull()?.validity() ?: 0) + + (if (logprobs.asKnown().isPresent) 1 else 0) + + (if (maxTokens.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (n.asKnown().isPresent) 1 else 0) + + (if (numRetries.asKnown().isPresent) 1 else 0) + + (if (parallelToolCalls.asKnown().isPresent) 1 else 0) + + (if (presencePenalty.asKnown().isPresent) 1 else 0) + + (responseFormat.asKnown().getOrNull()?.validity() ?: 0) + + (if (seed.asKnown().isPresent) 1 else 0) + + (if (serviceTier.asKnown().isPresent) 1 else 0) + + (stop.asKnown().getOrNull()?.validity() ?: 0) + + (if (stream.asKnown().isPresent) 1 else 0) + + (streamOptions.asKnown().getOrNull()?.validity() ?: 0) + + (if (temperature.asKnown().isPresent) 1 else 0) + + (toolChoice.asKnown().getOrNull()?.validity() ?: 0) + + (tools.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (topLogprobs.asKnown().isPresent) 1 else 0) + + (if (topP.asKnown().isPresent) 1 else 0) + + (if (user.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + messages == other.messages && + bodyModel == other.bodyModel && + caching == other.caching && + contextWindowFallbackDict == other.contextWindowFallbackDict && + fallbacks == other.fallbacks && + frequencyPenalty == other.frequencyPenalty && + functionCall == other.functionCall && + functions == other.functions && + guardrails == other.guardrails && + logitBias == other.logitBias && + logprobs == other.logprobs && + maxTokens == other.maxTokens && + metadata == other.metadata && + n == other.n && + numRetries == other.numRetries && + parallelToolCalls == other.parallelToolCalls && + presencePenalty == other.presencePenalty && + responseFormat == other.responseFormat && + seed == other.seed && + serviceTier == other.serviceTier && + stop == other.stop && + stream == other.stream && + streamOptions == other.streamOptions && + temperature == other.temperature && + toolChoice == other.toolChoice && + tools == other.tools && + topLogprobs == other.topLogprobs && + topP == other.topP && + user == other.user && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + messages, + bodyModel, + caching, + contextWindowFallbackDict, + fallbacks, + frequencyPenalty, + functionCall, + functions, + guardrails, + logitBias, + logprobs, + maxTokens, + metadata, + n, + numRetries, + parallelToolCalls, + presencePenalty, + responseFormat, + seed, + serviceTier, + stop, + stream, + streamOptions, + temperature, + toolChoice, + tools, + topLogprobs, + topP, + user, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{messages=$messages, bodyModel=$bodyModel, caching=$caching, contextWindowFallbackDict=$contextWindowFallbackDict, fallbacks=$fallbacks, frequencyPenalty=$frequencyPenalty, functionCall=$functionCall, functions=$functions, guardrails=$guardrails, logitBias=$logitBias, logprobs=$logprobs, maxTokens=$maxTokens, metadata=$metadata, n=$n, numRetries=$numRetries, parallelToolCalls=$parallelToolCalls, presencePenalty=$presencePenalty, responseFormat=$responseFormat, seed=$seed, serviceTier=$serviceTier, stop=$stop, stream=$stream, streamOptions=$streamOptions, temperature=$temperature, toolChoice=$toolChoice, tools=$tools, topLogprobs=$topLogprobs, topP=$topP, user=$user, additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = Message.Deserializer::class) + @JsonSerialize(using = Message.Serializer::class) + class Message + private constructor( + private val chatCompletionUser: ChatCompletionUserMessage? = null, + private val chatCompletionAssistant: ChatCompletionAssistantMessage? = null, + private val chatCompletionTool: ChatCompletionToolMessage? = null, + private val chatCompletionSystem: ChatCompletionSystemMessage? = null, + private val chatCompletionFunction: ChatCompletionFunctionMessage? = null, + private val chatCompletionDeveloper: ChatCompletionDeveloperMessage? = null, + private val _json: JsonValue? = null, + ) { + + fun chatCompletionUser(): Optional = + Optional.ofNullable(chatCompletionUser) + + fun chatCompletionAssistant(): Optional = + Optional.ofNullable(chatCompletionAssistant) + + fun chatCompletionTool(): Optional = + Optional.ofNullable(chatCompletionTool) + + fun chatCompletionSystem(): Optional = + Optional.ofNullable(chatCompletionSystem) + + fun chatCompletionFunction(): Optional = + Optional.ofNullable(chatCompletionFunction) + + fun chatCompletionDeveloper(): Optional = + Optional.ofNullable(chatCompletionDeveloper) + + fun isChatCompletionUser(): Boolean = chatCompletionUser != null + + fun isChatCompletionAssistant(): Boolean = chatCompletionAssistant != null + + fun isChatCompletionTool(): Boolean = chatCompletionTool != null + + fun isChatCompletionSystem(): Boolean = chatCompletionSystem != null + + fun isChatCompletionFunction(): Boolean = chatCompletionFunction != null + + fun isChatCompletionDeveloper(): Boolean = chatCompletionDeveloper != null + + fun asChatCompletionUser(): ChatCompletionUserMessage = + chatCompletionUser.getOrThrow("chatCompletionUser") + + fun asChatCompletionAssistant(): ChatCompletionAssistantMessage = + chatCompletionAssistant.getOrThrow("chatCompletionAssistant") + + fun asChatCompletionTool(): ChatCompletionToolMessage = + chatCompletionTool.getOrThrow("chatCompletionTool") + + fun asChatCompletionSystem(): ChatCompletionSystemMessage = + chatCompletionSystem.getOrThrow("chatCompletionSystem") + + fun asChatCompletionFunction(): ChatCompletionFunctionMessage = + chatCompletionFunction.getOrThrow("chatCompletionFunction") + + fun asChatCompletionDeveloper(): ChatCompletionDeveloperMessage = + chatCompletionDeveloper.getOrThrow("chatCompletionDeveloper") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + chatCompletionUser != null -> visitor.visitChatCompletionUser(chatCompletionUser) + chatCompletionAssistant != null -> + visitor.visitChatCompletionAssistant(chatCompletionAssistant) + chatCompletionTool != null -> visitor.visitChatCompletionTool(chatCompletionTool) + chatCompletionSystem != null -> + visitor.visitChatCompletionSystem(chatCompletionSystem) + chatCompletionFunction != null -> + visitor.visitChatCompletionFunction(chatCompletionFunction) + chatCompletionDeveloper != null -> + visitor.visitChatCompletionDeveloper(chatCompletionDeveloper) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Message = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitChatCompletionUser( + chatCompletionUser: ChatCompletionUserMessage + ) { + chatCompletionUser.validate() + } + + override fun visitChatCompletionAssistant( + chatCompletionAssistant: ChatCompletionAssistantMessage + ) { + chatCompletionAssistant.validate() + } + + override fun visitChatCompletionTool( + chatCompletionTool: ChatCompletionToolMessage + ) { + chatCompletionTool.validate() + } + + override fun visitChatCompletionSystem( + chatCompletionSystem: ChatCompletionSystemMessage + ) { + chatCompletionSystem.validate() + } + + override fun visitChatCompletionFunction( + chatCompletionFunction: ChatCompletionFunctionMessage + ) { + chatCompletionFunction.validate() + } + + override fun visitChatCompletionDeveloper( + chatCompletionDeveloper: ChatCompletionDeveloperMessage + ) { + chatCompletionDeveloper.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitChatCompletionUser( + chatCompletionUser: ChatCompletionUserMessage + ) = chatCompletionUser.validity() + + override fun visitChatCompletionAssistant( + chatCompletionAssistant: ChatCompletionAssistantMessage + ) = chatCompletionAssistant.validity() + + override fun visitChatCompletionTool( + chatCompletionTool: ChatCompletionToolMessage + ) = chatCompletionTool.validity() + + override fun visitChatCompletionSystem( + chatCompletionSystem: ChatCompletionSystemMessage + ) = chatCompletionSystem.validity() + + override fun visitChatCompletionFunction( + chatCompletionFunction: ChatCompletionFunctionMessage + ) = chatCompletionFunction.validity() + + override fun visitChatCompletionDeveloper( + chatCompletionDeveloper: ChatCompletionDeveloperMessage + ) = chatCompletionDeveloper.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Message && + chatCompletionUser == other.chatCompletionUser && + chatCompletionAssistant == other.chatCompletionAssistant && + chatCompletionTool == other.chatCompletionTool && + chatCompletionSystem == other.chatCompletionSystem && + chatCompletionFunction == other.chatCompletionFunction && + chatCompletionDeveloper == other.chatCompletionDeveloper + } + + override fun hashCode(): Int = + Objects.hash( + chatCompletionUser, + chatCompletionAssistant, + chatCompletionTool, + chatCompletionSystem, + chatCompletionFunction, + chatCompletionDeveloper, + ) + + override fun toString(): String = + when { + chatCompletionUser != null -> "Message{chatCompletionUser=$chatCompletionUser}" + chatCompletionAssistant != null -> + "Message{chatCompletionAssistant=$chatCompletionAssistant}" + chatCompletionTool != null -> "Message{chatCompletionTool=$chatCompletionTool}" + chatCompletionSystem != null -> + "Message{chatCompletionSystem=$chatCompletionSystem}" + chatCompletionFunction != null -> + "Message{chatCompletionFunction=$chatCompletionFunction}" + chatCompletionDeveloper != null -> + "Message{chatCompletionDeveloper=$chatCompletionDeveloper}" + _json != null -> "Message{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Message") + } + + companion object { + + @JvmStatic + fun ofChatCompletionUser(chatCompletionUser: ChatCompletionUserMessage) = + Message(chatCompletionUser = chatCompletionUser) + + @JvmStatic + fun ofChatCompletionAssistant(chatCompletionAssistant: ChatCompletionAssistantMessage) = + Message(chatCompletionAssistant = chatCompletionAssistant) + + @JvmStatic + fun ofChatCompletionTool(chatCompletionTool: ChatCompletionToolMessage) = + Message(chatCompletionTool = chatCompletionTool) + + @JvmStatic + fun ofChatCompletionSystem(chatCompletionSystem: ChatCompletionSystemMessage) = + Message(chatCompletionSystem = chatCompletionSystem) + + @JvmStatic + fun ofChatCompletionFunction(chatCompletionFunction: ChatCompletionFunctionMessage) = + Message(chatCompletionFunction = chatCompletionFunction) + + @JvmStatic + fun ofChatCompletionDeveloper(chatCompletionDeveloper: ChatCompletionDeveloperMessage) = + Message(chatCompletionDeveloper = chatCompletionDeveloper) + } + + /** + * An interface that defines how to map each variant of [Message] to a value of type [T]. + */ + interface Visitor { + + fun visitChatCompletionUser(chatCompletionUser: ChatCompletionUserMessage): T + + fun visitChatCompletionAssistant( + chatCompletionAssistant: ChatCompletionAssistantMessage + ): T + + fun visitChatCompletionTool(chatCompletionTool: ChatCompletionToolMessage): T + + fun visitChatCompletionSystem(chatCompletionSystem: ChatCompletionSystemMessage): T + + fun visitChatCompletionFunction( + chatCompletionFunction: ChatCompletionFunctionMessage + ): T + + fun visitChatCompletionDeveloper( + chatCompletionDeveloper: ChatCompletionDeveloperMessage + ): T + + /** + * Maps an unknown variant of [Message] to a value of type [T]. + * + * An instance of [Message] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Message: $json") + } + } + + internal class Deserializer : BaseDeserializer(Message::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Message { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Message(chatCompletionUser = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { Message(chatCompletionAssistant = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef())?.let { + Message(chatCompletionTool = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { Message(chatCompletionSystem = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { Message(chatCompletionFunction = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { Message(chatCompletionDeveloper = it, _json = json) }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> Message(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Message::class) { + + override fun serialize( + value: Message, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.chatCompletionUser != null -> + generator.writeObject(value.chatCompletionUser) + value.chatCompletionAssistant != null -> + generator.writeObject(value.chatCompletionAssistant) + value.chatCompletionTool != null -> + generator.writeObject(value.chatCompletionTool) + value.chatCompletionSystem != null -> + generator.writeObject(value.chatCompletionSystem) + value.chatCompletionFunction != null -> + generator.writeObject(value.chatCompletionFunction) + value.chatCompletionDeveloper != null -> + generator.writeObject(value.chatCompletionDeveloper) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Message") + } + } + } + + class ChatCompletionUserMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val content: JsonField, + private val role: JsonValue, + private val cacheControl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + ) : this(content, role, cacheControl, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun content(): Content = content.getRequired("content") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("user") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun cacheControl(): Optional = cacheControl.getOptional("cache_control") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionUserMessage]. + * + * The following fields are required: + * ```java + * .content() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionUserMessage]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var role: JsonValue = JsonValue.from("user") + private var cacheControl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionUserMessage: ChatCompletionUserMessage) = apply { + content = chatCompletionUserMessage.content + role = chatCompletionUserMessage.role + cacheControl = chatCompletionUserMessage.cacheControl + additionalProperties = + chatCompletionUserMessage.additionalProperties.toMutableMap() + } + + fun content(content: Content) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** + * Alias for calling [content] with + * `Content.ofUnnamedSchemaWithArrayParent2s(unnamedSchemaWithArrayParent2s)`. + */ + fun contentOfUnnamedSchemaWithArrayParent2s( + unnamedSchemaWithArrayParent2s: List + ) = + content( + Content.ofUnnamedSchemaWithArrayParent2s(unnamedSchemaWithArrayParent2s) + ) + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("user") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed [CacheControl] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionUserMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionUserMessage = + ChatCompletionUserMessage( + checkRequired("content", content), + role, + cacheControl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionUserMessage = apply { + if (validated) { + return@apply + } + + content().validate() + _role().let { + if (it != JsonValue.from("user")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (content.asKnown().getOrNull()?.validity() ?: 0) + + role.let { if (it == JsonValue.from("user")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val unnamedSchemaWithArrayParent2s: List? = + null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun unnamedSchemaWithArrayParent2s(): + Optional> = + Optional.ofNullable(unnamedSchemaWithArrayParent2s) + + fun isString(): Boolean = string != null + + fun isUnnamedSchemaWithArrayParent2s(): Boolean = + unnamedSchemaWithArrayParent2s != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnnamedSchemaWithArrayParent2s(): List = + unnamedSchemaWithArrayParent2s.getOrThrow("unnamedSchemaWithArrayParent2s") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + unnamedSchemaWithArrayParent2s != null -> + visitor.visitUnnamedSchemaWithArrayParent2s( + unnamedSchemaWithArrayParent2s + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitUnnamedSchemaWithArrayParent2s( + unnamedSchemaWithArrayParent2s: List + ) { + unnamedSchemaWithArrayParent2s.forEach { it.validate() } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitUnnamedSchemaWithArrayParent2s( + unnamedSchemaWithArrayParent2s: List + ) = unnamedSchemaWithArrayParent2s.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + unnamedSchemaWithArrayParent2s == other.unnamedSchemaWithArrayParent2s + } + + override fun hashCode(): Int = Objects.hash(string, unnamedSchemaWithArrayParent2s) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + unnamedSchemaWithArrayParent2s != null -> + "Content{unnamedSchemaWithArrayParent2s=$unnamedSchemaWithArrayParent2s}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofUnnamedSchemaWithArrayParent2s( + unnamedSchemaWithArrayParent2s: List + ) = + Content( + unnamedSchemaWithArrayParent2s = + unnamedSchemaWithArrayParent2s.toImmutable() + ) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitUnnamedSchemaWithArrayParent2s( + unnamedSchemaWithArrayParent2s: List + ): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { + Content( + unnamedSchemaWithArrayParent2s = it, + _json = json, + ) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unnamedSchemaWithArrayParent2s != null -> + generator.writeObject(value.unnamedSchemaWithArrayParent2s) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + + @JsonDeserialize(using = UnnamedSchemaWithArrayParent2.Deserializer::class) + @JsonSerialize(using = UnnamedSchemaWithArrayParent2.Serializer::class) + class UnnamedSchemaWithArrayParent2 + private constructor( + private val chatCompletionTextObject: ChatCompletionTextObject? = null, + private val chatCompletionImageObject: ChatCompletionImageObject? = null, + private val chatCompletionAudioObject: ChatCompletionAudioObject? = null, + private val chatCompletionDocumentObject: ChatCompletionDocumentObject? = null, + private val chatCompletionVideoObject: ChatCompletionVideoObject? = null, + private val chatCompletionFileObject: ChatCompletionFileObject? = null, + private val _json: JsonValue? = null, + ) { + + fun chatCompletionTextObject(): Optional = + Optional.ofNullable(chatCompletionTextObject) + + fun chatCompletionImageObject(): Optional = + Optional.ofNullable(chatCompletionImageObject) + + fun chatCompletionAudioObject(): Optional = + Optional.ofNullable(chatCompletionAudioObject) + + fun chatCompletionDocumentObject(): Optional = + Optional.ofNullable(chatCompletionDocumentObject) + + fun chatCompletionVideoObject(): Optional = + Optional.ofNullable(chatCompletionVideoObject) + + fun chatCompletionFileObject(): Optional = + Optional.ofNullable(chatCompletionFileObject) + + fun isChatCompletionTextObject(): Boolean = chatCompletionTextObject != null + + fun isChatCompletionImageObject(): Boolean = chatCompletionImageObject != null + + fun isChatCompletionAudioObject(): Boolean = chatCompletionAudioObject != null + + fun isChatCompletionDocumentObject(): Boolean = + chatCompletionDocumentObject != null + + fun isChatCompletionVideoObject(): Boolean = chatCompletionVideoObject != null + + fun isChatCompletionFileObject(): Boolean = chatCompletionFileObject != null + + fun asChatCompletionTextObject(): ChatCompletionTextObject = + chatCompletionTextObject.getOrThrow("chatCompletionTextObject") + + fun asChatCompletionImageObject(): ChatCompletionImageObject = + chatCompletionImageObject.getOrThrow("chatCompletionImageObject") + + fun asChatCompletionAudioObject(): ChatCompletionAudioObject = + chatCompletionAudioObject.getOrThrow("chatCompletionAudioObject") + + fun asChatCompletionDocumentObject(): ChatCompletionDocumentObject = + chatCompletionDocumentObject.getOrThrow("chatCompletionDocumentObject") + + fun asChatCompletionVideoObject(): ChatCompletionVideoObject = + chatCompletionVideoObject.getOrThrow("chatCompletionVideoObject") + + fun asChatCompletionFileObject(): ChatCompletionFileObject = + chatCompletionFileObject.getOrThrow("chatCompletionFileObject") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + chatCompletionTextObject != null -> + visitor.visitChatCompletionTextObject(chatCompletionTextObject) + chatCompletionImageObject != null -> + visitor.visitChatCompletionImageObject(chatCompletionImageObject) + chatCompletionAudioObject != null -> + visitor.visitChatCompletionAudioObject(chatCompletionAudioObject) + chatCompletionDocumentObject != null -> + visitor.visitChatCompletionDocumentObject( + chatCompletionDocumentObject + ) + chatCompletionVideoObject != null -> + visitor.visitChatCompletionVideoObject(chatCompletionVideoObject) + chatCompletionFileObject != null -> + visitor.visitChatCompletionFileObject(chatCompletionFileObject) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnnamedSchemaWithArrayParent2 = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) { + chatCompletionTextObject.validate() + } + + override fun visitChatCompletionImageObject( + chatCompletionImageObject: ChatCompletionImageObject + ) { + chatCompletionImageObject.validate() + } + + override fun visitChatCompletionAudioObject( + chatCompletionAudioObject: ChatCompletionAudioObject + ) { + chatCompletionAudioObject.validate() + } + + override fun visitChatCompletionDocumentObject( + chatCompletionDocumentObject: ChatCompletionDocumentObject + ) { + chatCompletionDocumentObject.validate() + } + + override fun visitChatCompletionVideoObject( + chatCompletionVideoObject: ChatCompletionVideoObject + ) { + chatCompletionVideoObject.validate() + } + + override fun visitChatCompletionFileObject( + chatCompletionFileObject: ChatCompletionFileObject + ) { + chatCompletionFileObject.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) = chatCompletionTextObject.validity() + + override fun visitChatCompletionImageObject( + chatCompletionImageObject: ChatCompletionImageObject + ) = chatCompletionImageObject.validity() + + override fun visitChatCompletionAudioObject( + chatCompletionAudioObject: ChatCompletionAudioObject + ) = chatCompletionAudioObject.validity() + + override fun visitChatCompletionDocumentObject( + chatCompletionDocumentObject: ChatCompletionDocumentObject + ) = chatCompletionDocumentObject.validity() + + override fun visitChatCompletionVideoObject( + chatCompletionVideoObject: ChatCompletionVideoObject + ) = chatCompletionVideoObject.validity() + + override fun visitChatCompletionFileObject( + chatCompletionFileObject: ChatCompletionFileObject + ) = chatCompletionFileObject.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnnamedSchemaWithArrayParent2 && + chatCompletionTextObject == other.chatCompletionTextObject && + chatCompletionImageObject == other.chatCompletionImageObject && + chatCompletionAudioObject == other.chatCompletionAudioObject && + chatCompletionDocumentObject == other.chatCompletionDocumentObject && + chatCompletionVideoObject == other.chatCompletionVideoObject && + chatCompletionFileObject == other.chatCompletionFileObject + } + + override fun hashCode(): Int = + Objects.hash( + chatCompletionTextObject, + chatCompletionImageObject, + chatCompletionAudioObject, + chatCompletionDocumentObject, + chatCompletionVideoObject, + chatCompletionFileObject, + ) + + override fun toString(): String = + when { + chatCompletionTextObject != null -> + "UnnamedSchemaWithArrayParent2{chatCompletionTextObject=$chatCompletionTextObject}" + chatCompletionImageObject != null -> + "UnnamedSchemaWithArrayParent2{chatCompletionImageObject=$chatCompletionImageObject}" + chatCompletionAudioObject != null -> + "UnnamedSchemaWithArrayParent2{chatCompletionAudioObject=$chatCompletionAudioObject}" + chatCompletionDocumentObject != null -> + "UnnamedSchemaWithArrayParent2{chatCompletionDocumentObject=$chatCompletionDocumentObject}" + chatCompletionVideoObject != null -> + "UnnamedSchemaWithArrayParent2{chatCompletionVideoObject=$chatCompletionVideoObject}" + chatCompletionFileObject != null -> + "UnnamedSchemaWithArrayParent2{chatCompletionFileObject=$chatCompletionFileObject}" + _json != null -> "UnnamedSchemaWithArrayParent2{_unknown=$_json}" + else -> + throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent2") + } + + companion object { + + @JvmStatic + fun ofChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) = + UnnamedSchemaWithArrayParent2( + chatCompletionTextObject = chatCompletionTextObject + ) + + @JvmStatic + fun ofChatCompletionImageObject( + chatCompletionImageObject: ChatCompletionImageObject + ) = + UnnamedSchemaWithArrayParent2( + chatCompletionImageObject = chatCompletionImageObject + ) + + @JvmStatic + fun ofChatCompletionAudioObject( + chatCompletionAudioObject: ChatCompletionAudioObject + ) = + UnnamedSchemaWithArrayParent2( + chatCompletionAudioObject = chatCompletionAudioObject + ) + + @JvmStatic + fun ofChatCompletionDocumentObject( + chatCompletionDocumentObject: ChatCompletionDocumentObject + ) = + UnnamedSchemaWithArrayParent2( + chatCompletionDocumentObject = chatCompletionDocumentObject + ) + + @JvmStatic + fun ofChatCompletionVideoObject( + chatCompletionVideoObject: ChatCompletionVideoObject + ) = + UnnamedSchemaWithArrayParent2( + chatCompletionVideoObject = chatCompletionVideoObject + ) + + @JvmStatic + fun ofChatCompletionFileObject( + chatCompletionFileObject: ChatCompletionFileObject + ) = + UnnamedSchemaWithArrayParent2( + chatCompletionFileObject = chatCompletionFileObject + ) + } + + /** + * An interface that defines how to map each variant of + * [UnnamedSchemaWithArrayParent2] to a value of type [T]. + */ + interface Visitor { + + fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ): T + + fun visitChatCompletionImageObject( + chatCompletionImageObject: ChatCompletionImageObject + ): T + + fun visitChatCompletionAudioObject( + chatCompletionAudioObject: ChatCompletionAudioObject + ): T + + fun visitChatCompletionDocumentObject( + chatCompletionDocumentObject: ChatCompletionDocumentObject + ): T + + fun visitChatCompletionVideoObject( + chatCompletionVideoObject: ChatCompletionVideoObject + ): T + + fun visitChatCompletionFileObject( + chatCompletionFileObject: ChatCompletionFileObject + ): T + + /** + * Maps an unknown variant of [UnnamedSchemaWithArrayParent2] to a value of + * type [T]. + * + * An instance of [UnnamedSchemaWithArrayParent2] can contain an unknown + * variant if it was deserialized from data that doesn't match any known + * variant. For example, if the SDK is on an older version than the API, + * then the API may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException( + "Unknown UnnamedSchemaWithArrayParent2: $json" + ) + } + } + + internal class Deserializer : + BaseDeserializer( + UnnamedSchemaWithArrayParent2::class + ) { + + override fun ObjectCodec.deserialize( + node: JsonNode + ): UnnamedSchemaWithArrayParent2 { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent2( + chatCompletionTextObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent2( + chatCompletionImageObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent2( + chatCompletionAudioObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent2( + chatCompletionDocumentObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent2( + chatCompletionVideoObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent2( + chatCompletionFileObject = it, + _json = json, + ) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing + // from boolean). + 0 -> UnnamedSchemaWithArrayParent2(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then + // use the first completely valid match, or simply the first match + // if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer( + UnnamedSchemaWithArrayParent2::class + ) { + + override fun serialize( + value: UnnamedSchemaWithArrayParent2, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.chatCompletionTextObject != null -> + generator.writeObject(value.chatCompletionTextObject) + value.chatCompletionImageObject != null -> + generator.writeObject(value.chatCompletionImageObject) + value.chatCompletionAudioObject != null -> + generator.writeObject(value.chatCompletionAudioObject) + value.chatCompletionDocumentObject != null -> + generator.writeObject(value.chatCompletionDocumentObject) + value.chatCompletionVideoObject != null -> + generator.writeObject(value.chatCompletionVideoObject) + value.chatCompletionFileObject != null -> + generator.writeObject(value.chatCompletionFileObject) + value._json != null -> generator.writeObject(value._json) + else -> + throw IllegalStateException( + "Invalid UnnamedSchemaWithArrayParent2" + ) + } + } + } + + class ChatCompletionTextObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val text: JsonField, + private val type: JsonValue, + private val cacheControl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("text") + @ExcludeMissing + text: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + ) : this(text, type, cacheControl, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun text(): String = text.getRequired("text") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("text") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * Returns the raw JSON value of [text]. + * + * Unlike [text], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("text") @ExcludeMissing fun _text(): JsonField = text + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionTextObject]. + * + * The following fields are required: + * ```java + * .text() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionTextObject]. */ + class Builder internal constructor() { + + private var text: JsonField? = null + private var type: JsonValue = JsonValue.from("text") + private var cacheControl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionTextObject: ChatCompletionTextObject) = + apply { + text = chatCompletionTextObject.text + type = chatCompletionTextObject.type + cacheControl = chatCompletionTextObject.cacheControl + additionalProperties = + chatCompletionTextObject.additionalProperties.toMutableMap() + } + + fun text(text: String) = text(JsonField.of(text)) + + /** + * Sets [Builder.text] to an arbitrary JSON value. + * + * You should usually call [Builder.text] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun text(text: JsonField) = apply { this.text = text } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("text") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionTextObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .text() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionTextObject = + ChatCompletionTextObject( + checkRequired("text", text), + type, + cacheControl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionTextObject = apply { + if (validated) { + return@apply + } + + text() + _type().let { + if (it != JsonValue.from("text")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + cacheControl().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (text.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("text")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if + * the server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [CacheControl]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = + cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionTextObject && + text == other.text && + type == other.type && + cacheControl == other.cacheControl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(text, type, cacheControl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionTextObject{text=$text, type=$type, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" + } + + class ChatCompletionImageObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val imageUrl: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("image_url") + @ExcludeMissing + imageUrl: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + ) : this(imageUrl, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun imageUrl(): ImageUrl = imageUrl.getRequired("image_url") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("image_url") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [imageUrl]. + * + * Unlike [imageUrl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("image_url") + @ExcludeMissing + fun _imageUrl(): JsonField = imageUrl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionImageObject]. + * + * The following fields are required: + * ```java + * .imageUrl() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionImageObject]. */ + class Builder internal constructor() { + + private var imageUrl: JsonField? = null + private var type: JsonValue = JsonValue.from("image_url") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionImageObject: ChatCompletionImageObject + ) = apply { + imageUrl = chatCompletionImageObject.imageUrl + type = chatCompletionImageObject.type + additionalProperties = + chatCompletionImageObject.additionalProperties.toMutableMap() + } + + fun imageUrl(imageUrl: ImageUrl) = imageUrl(JsonField.of(imageUrl)) + + /** + * Sets [Builder.imageUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.imageUrl] with a well-typed + * [ImageUrl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun imageUrl(imageUrl: JsonField) = apply { + this.imageUrl = imageUrl + } + + /** Alias for calling [imageUrl] with `ImageUrl.ofString(string)`. */ + fun imageUrl(string: String) = imageUrl(ImageUrl.ofString(string)) + + /** + * Alias for calling [imageUrl] with + * `ImageUrl.ofChatCompletionImageUrlObject(chatCompletionImageUrlObject)`. + */ + fun imageUrl( + chatCompletionImageUrlObject: ImageUrl.ChatCompletionImageUrlObject + ) = + imageUrl( + ImageUrl.ofChatCompletionImageUrlObject( + chatCompletionImageUrlObject + ) + ) + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("image_url") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionImageObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .imageUrl() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionImageObject = + ChatCompletionImageObject( + checkRequired("imageUrl", imageUrl), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionImageObject = apply { + if (validated) { + return@apply + } + + imageUrl().validate() + _type().let { + if (it != JsonValue.from("image_url")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (imageUrl.asKnown().getOrNull()?.validity() ?: 0) + + type.let { if (it == JsonValue.from("image_url")) 1 else 0 } + + @JsonDeserialize(using = ImageUrl.Deserializer::class) + @JsonSerialize(using = ImageUrl.Serializer::class) + class ImageUrl + private constructor( + private val string: String? = null, + private val chatCompletionImageUrlObject: + ChatCompletionImageUrlObject? = + null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun chatCompletionImageUrlObject(): + Optional = + Optional.ofNullable(chatCompletionImageUrlObject) + + fun isString(): Boolean = string != null + + fun isChatCompletionImageUrlObject(): Boolean = + chatCompletionImageUrlObject != null + + fun asString(): String = string.getOrThrow("string") + + fun asChatCompletionImageUrlObject(): ChatCompletionImageUrlObject = + chatCompletionImageUrlObject.getOrThrow( + "chatCompletionImageUrlObject" + ) + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + chatCompletionImageUrlObject != null -> + visitor.visitChatCompletionImageUrlObject( + chatCompletionImageUrlObject + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): ImageUrl = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitChatCompletionImageUrlObject( + chatCompletionImageUrlObject: + ChatCompletionImageUrlObject + ) { + chatCompletionImageUrlObject.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitChatCompletionImageUrlObject( + chatCompletionImageUrlObject: + ChatCompletionImageUrlObject + ) = chatCompletionImageUrlObject.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ImageUrl && + string == other.string && + chatCompletionImageUrlObject == + other.chatCompletionImageUrlObject + } + + override fun hashCode(): Int = + Objects.hash(string, chatCompletionImageUrlObject) + + override fun toString(): String = + when { + string != null -> "ImageUrl{string=$string}" + chatCompletionImageUrlObject != null -> + "ImageUrl{chatCompletionImageUrlObject=$chatCompletionImageUrlObject}" + _json != null -> "ImageUrl{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ImageUrl") + } + + companion object { + + @JvmStatic fun ofString(string: String) = ImageUrl(string = string) + + @JvmStatic + fun ofChatCompletionImageUrlObject( + chatCompletionImageUrlObject: ChatCompletionImageUrlObject + ) = + ImageUrl( + chatCompletionImageUrlObject = chatCompletionImageUrlObject + ) + } + + /** + * An interface that defines how to map each variant of [ImageUrl] to a + * value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitChatCompletionImageUrlObject( + chatCompletionImageUrlObject: ChatCompletionImageUrlObject + ): T + + /** + * Maps an unknown variant of [ImageUrl] to a value of type [T]. + * + * An instance of [ImageUrl] can contain an unknown variant if it + * was deserialized from data that doesn't match any known variant. + * For example, if the SDK is on an older version than the API, then + * the API may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown ImageUrl: $json") + } + } + + internal class Deserializer : + BaseDeserializer(ImageUrl::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): ImageUrl { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef< + ChatCompletionImageUrlObject + >(), + ) + ?.let { + ImageUrl( + chatCompletionImageUrlObject = it, + _json = json, + ) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { ImageUrl(string = it, _json = json) }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. + // deserializing from boolean). + 0 -> ImageUrl(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, + // then use the first completely valid match, or simply the + // first match if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } + ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(ImageUrl::class) { + + override fun serialize( + value: ImageUrl, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.chatCompletionImageUrlObject != null -> + generator.writeObject( + value.chatCompletionImageUrlObject + ) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid ImageUrl") + } + } + } + + class ChatCompletionImageUrlObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val url: JsonField, + private val detail: JsonField, + private val format: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") + @ExcludeMissing + url: JsonField = JsonMissing.of(), + @JsonProperty("detail") + @ExcludeMissing + detail: JsonField = JsonMissing.of(), + @JsonProperty("format") + @ExcludeMissing + format: JsonField = JsonMissing.of(), + ) : this(url, detail, format, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an + * unexpected type or is unexpectedly missing or null (e.g. if the + * server responded with an unexpected value). + */ + fun url(): String = url.getRequired("url") + + /** + * @throws HanzoInvalidDataException if the JSON field has an + * unexpected type (e.g. if the server responded with an + * unexpected value). + */ + fun detail(): Optional = detail.getOptional("detail") + + /** + * @throws HanzoInvalidDataException if the JSON field has an + * unexpected type (e.g. if the server responded with an + * unexpected value). + */ + fun format(): Optional = format.getOptional("format") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("url") + @ExcludeMissing + fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [detail]. + * + * Unlike [detail], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("detail") + @ExcludeMissing + fun _detail(): JsonField = detail + + /** + * Returns the raw JSON value of [format]. + * + * Unlike [format], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("format") + @ExcludeMissing + fun _format(): JsonField = format + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionImageUrlObject]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionImageUrlObject]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var detail: JsonField = JsonMissing.of() + private var format: JsonField = JsonMissing.of() + private var additionalProperties: + MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionImageUrlObject: ChatCompletionImageUrlObject + ) = apply { + url = chatCompletionImageUrlObject.url + detail = chatCompletionImageUrlObject.detail + format = chatCompletionImageUrlObject.format + additionalProperties = + chatCompletionImageUrlObject.additionalProperties + .toMutableMap() + } + + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed + * [String] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun detail(detail: String) = detail(JsonField.of(detail)) + + /** + * Sets [Builder.detail] to an arbitrary JSON value. + * + * You should usually call [Builder.detail] with a well-typed + * [String] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun detail(detail: JsonField) = apply { + this.detail = detail + } + + fun format(format: String) = format(JsonField.of(format)) + + /** + * Sets [Builder.format] to an arbitrary JSON value. + * + * You should usually call [Builder.format] with a well-typed + * [String] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun format(format: JsonField) = apply { + this.format = format + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = + apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of + * [ChatCompletionImageUrlObject]. + * + * Further updates to this [Builder] will not mutate the + * returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionImageUrlObject = + ChatCompletionImageUrlObject( + checkRequired("url", url), + detail, + format, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionImageUrlObject = apply { + if (validated) { + return@apply + } + + url() + detail() + format() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (url.asKnown().isPresent) 1 else 0) + + (if (detail.asKnown().isPresent) 1 else 0) + + (if (format.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionImageUrlObject && + url == other.url && + detail == other.detail && + format == other.format && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(url, detail, format, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionImageUrlObject{url=$url, detail=$detail, format=$format, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionImageObject && + imageUrl == other.imageUrl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(imageUrl, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionImageObject{imageUrl=$imageUrl, type=$type, additionalProperties=$additionalProperties}" + } + + class ChatCompletionAudioObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val inputAudio: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("input_audio") + @ExcludeMissing + inputAudio: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + ) : this(inputAudio, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun inputAudio(): InputAudio = inputAudio.getRequired("input_audio") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("input_audio") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [inputAudio]. + * + * Unlike [inputAudio], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("input_audio") + @ExcludeMissing + fun _inputAudio(): JsonField = inputAudio + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionAudioObject]. + * + * The following fields are required: + * ```java + * .inputAudio() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionAudioObject]. */ + class Builder internal constructor() { + + private var inputAudio: JsonField? = null + private var type: JsonValue = JsonValue.from("input_audio") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionAudioObject: ChatCompletionAudioObject + ) = apply { + inputAudio = chatCompletionAudioObject.inputAudio + type = chatCompletionAudioObject.type + additionalProperties = + chatCompletionAudioObject.additionalProperties.toMutableMap() + } + + fun inputAudio(inputAudio: InputAudio) = + inputAudio(JsonField.of(inputAudio)) + + /** + * Sets [Builder.inputAudio] to an arbitrary JSON value. + * + * You should usually call [Builder.inputAudio] with a well-typed + * [InputAudio] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun inputAudio(inputAudio: JsonField) = apply { + this.inputAudio = inputAudio + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("input_audio") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionAudioObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .inputAudio() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionAudioObject = + ChatCompletionAudioObject( + checkRequired("inputAudio", inputAudio), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionAudioObject = apply { + if (validated) { + return@apply + } + + inputAudio().validate() + _type().let { + if (it != JsonValue.from("input_audio")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (inputAudio.asKnown().getOrNull()?.validity() ?: 0) + + type.let { if (it == JsonValue.from("input_audio")) 1 else 0 } + + class InputAudio + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val data: JsonField, + private val format: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("data") + @ExcludeMissing + data: JsonField = JsonMissing.of(), + @JsonProperty("format") + @ExcludeMissing + format: JsonField = JsonMissing.of(), + ) : this(data, format, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server + * responded with an unexpected value). + */ + fun data(): String = data.getRequired("data") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server + * responded with an unexpected value). + */ + fun format(): Format = format.getRequired("format") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("data") + @ExcludeMissing + fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [format]. + * + * Unlike [format], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("format") + @ExcludeMissing + fun _format(): JsonField = format + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [InputAudio]. + * + * The following fields are required: + * ```java + * .data() + * .format() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InputAudio]. */ + class Builder internal constructor() { + + private var data: JsonField? = null + private var format: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(inputAudio: InputAudio) = apply { + data = inputAudio.data + format = inputAudio.format + additionalProperties = + inputAudio.additionalProperties.toMutableMap() + } + + fun data(data: String) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] + * value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + fun format(format: Format) = format(JsonField.of(format)) + + /** + * Sets [Builder.format] to an arbitrary JSON value. + * + * You should usually call [Builder.format] with a well-typed + * [Format] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun format(format: JsonField) = apply { + this.format = format + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InputAudio]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .data() + * .format() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InputAudio = + InputAudio( + checkRequired("data", data), + checkRequired("format", format), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): InputAudio = apply { + if (validated) { + return@apply + } + + data() + format().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (format.asKnown().getOrNull()?.validity() ?: 0) + + class Format + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized + * from data that doesn't match any known member, and you want to + * know that value. For example, if the SDK is on an older version + * than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val WAV = of("wav") + + @JvmField val MP3 = of("mp3") + + @JvmStatic fun of(value: String) = Format(JsonField.of(value)) + } + + /** An enum containing [Format]'s known values. */ + enum class Known { + WAV, + MP3, + } + + /** + * An enum containing [Format]'s known values, as well as an + * [_UNKNOWN] member. + * + * An instance of [Format] can contain an unknown value in a couple + * of cases: + * - It was deserialized from data that doesn't match any known + * member. For example, if the SDK is on an older version than the + * API, then the API may respond with new members that the SDK is + * unaware of. + * - It was constructed with an arbitrary value using the [of] + * method. + */ + enum class Value { + WAV, + MP3, + /** + * An enum member indicating that [Format] was instantiated with + * an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's + * value, or [Value._UNKNOWN] if the class was instantiated with an + * unknown value. + * + * Use the [known] method instead if you're certain the value is + * always known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + WAV -> Value.WAV + MP3 -> Value.MP3 + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's + * value. + * + * Use the [value] method instead if you're uncertain the value is + * always known and don't want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value + * is a not a known member. + */ + fun known(): Known = + when (this) { + WAV -> Known.WAV + MP3 -> Known.MP3 + else -> + throw HanzoInvalidDataException( + "Unknown Format: $value" + ) + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is + * primarily for debugging and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + HanzoInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Format = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Format && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InputAudio && + data == other.data && + format == other.format && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(data, format, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InputAudio{data=$data, format=$format, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionAudioObject && + inputAudio == other.inputAudio && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(inputAudio, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionAudioObject{inputAudio=$inputAudio, type=$type, additionalProperties=$additionalProperties}" + } + + class ChatCompletionDocumentObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val citations: JsonField, + private val context: JsonField, + private val source: JsonField, + private val title: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("citations") + @ExcludeMissing + citations: JsonField = JsonMissing.of(), + @JsonProperty("context") + @ExcludeMissing + context: JsonField = JsonMissing.of(), + @JsonProperty("source") + @ExcludeMissing + source: JsonField = JsonMissing.of(), + @JsonProperty("title") + @ExcludeMissing + title: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + ) : this(citations, context, source, title, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun citations(): Optional = citations.getOptional("citations") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun context(): String = context.getRequired("context") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun source(): Source = source.getRequired("source") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun title(): String = title.getRequired("title") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("document") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [citations]. + * + * Unlike [citations], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("citations") + @ExcludeMissing + fun _citations(): JsonField = citations + + /** + * Returns the raw JSON value of [context]. + * + * Unlike [context], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("context") + @ExcludeMissing + fun _context(): JsonField = context + + /** + * Returns the raw JSON value of [source]. + * + * Unlike [source], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("source") + @ExcludeMissing + fun _source(): JsonField = source + + /** + * Returns the raw JSON value of [title]. + * + * Unlike [title], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("title") + @ExcludeMissing + fun _title(): JsonField = title + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionDocumentObject]. + * + * The following fields are required: + * ```java + * .citations() + * .context() + * .source() + * .title() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionDocumentObject]. */ + class Builder internal constructor() { + + private var citations: JsonField? = null + private var context: JsonField? = null + private var source: JsonField? = null + private var title: JsonField? = null + private var type: JsonValue = JsonValue.from("document") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionDocumentObject: ChatCompletionDocumentObject + ) = apply { + citations = chatCompletionDocumentObject.citations + context = chatCompletionDocumentObject.context + source = chatCompletionDocumentObject.source + title = chatCompletionDocumentObject.title + type = chatCompletionDocumentObject.type + additionalProperties = + chatCompletionDocumentObject.additionalProperties.toMutableMap() + } + + fun citations(citations: Citations?) = + citations(JsonField.ofNullable(citations)) + + /** + * Alias for calling [Builder.citations] with `citations.orElse(null)`. + */ + fun citations(citations: Optional) = + citations(citations.getOrNull()) + + /** + * Sets [Builder.citations] to an arbitrary JSON value. + * + * You should usually call [Builder.citations] with a well-typed + * [Citations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun citations(citations: JsonField) = apply { + this.citations = citations + } + + fun context(context: String) = context(JsonField.of(context)) + + /** + * Sets [Builder.context] to an arbitrary JSON value. + * + * You should usually call [Builder.context] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun context(context: JsonField) = apply { + this.context = context + } + + fun source(source: Source) = source(JsonField.of(source)) + + /** + * Sets [Builder.source] to an arbitrary JSON value. + * + * You should usually call [Builder.source] with a well-typed [Source] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun source(source: JsonField) = apply { this.source = source } + + fun title(title: String) = title(JsonField.of(title)) + + /** + * Sets [Builder.title] to an arbitrary JSON value. + * + * You should usually call [Builder.title] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun title(title: JsonField) = apply { this.title = title } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("document") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionDocumentObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .citations() + * .context() + * .source() + * .title() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionDocumentObject = + ChatCompletionDocumentObject( + checkRequired("citations", citations), + checkRequired("context", context), + checkRequired("source", source), + checkRequired("title", title), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionDocumentObject = apply { + if (validated) { + return@apply + } + + citations().ifPresent { it.validate() } + context() + source().validate() + title() + _type().let { + if (it != JsonValue.from("document")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (citations.asKnown().getOrNull()?.validity() ?: 0) + + (if (context.asKnown().isPresent) 1 else 0) + + (source.asKnown().getOrNull()?.validity() ?: 0) + + (if (title.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("document")) 1 else 0 } + + class Citations + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val enabled: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("enabled") + @ExcludeMissing + enabled: JsonField = JsonMissing.of() + ) : this(enabled, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server + * responded with an unexpected value). + */ + fun enabled(): Boolean = enabled.getRequired("enabled") + + /** + * Returns the raw JSON value of [enabled]. + * + * Unlike [enabled], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("enabled") + @ExcludeMissing + fun _enabled(): JsonField = enabled + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [Citations]. + * + * The following fields are required: + * ```java + * .enabled() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Citations]. */ + class Builder internal constructor() { + + private var enabled: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(citations: Citations) = apply { + enabled = citations.enabled + additionalProperties = + citations.additionalProperties.toMutableMap() + } + + fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) + + /** + * Sets [Builder.enabled] to an arbitrary JSON value. + * + * You should usually call [Builder.enabled] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun enabled(enabled: JsonField) = apply { + this.enabled = enabled + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Citations]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .enabled() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Citations = + Citations( + checkRequired("enabled", enabled), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Citations = apply { + if (validated) { + return@apply + } + + enabled() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (enabled.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Citations && + enabled == other.enabled && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(enabled, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Citations{enabled=$enabled, additionalProperties=$additionalProperties}" + } + + class Source + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val data: JsonField, + private val mediaType: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("data") + @ExcludeMissing + data: JsonField = JsonMissing.of(), + @JsonProperty("media_type") + @ExcludeMissing + mediaType: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of(), + ) : this(data, mediaType, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server + * responded with an unexpected value). + */ + fun data(): String = data.getRequired("data") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server + * responded with an unexpected value). + */ + fun mediaType(): String = mediaType.getRequired("media_type") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("text") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if + * the server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("data") + @ExcludeMissing + fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [mediaType]. + * + * Unlike [mediaType], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("media_type") + @ExcludeMissing + fun _mediaType(): JsonField = mediaType + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [Source]. + * + * The following fields are required: + * ```java + * .data() + * .mediaType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Source]. */ + class Builder internal constructor() { + + private var data: JsonField? = null + private var mediaType: JsonField? = null + private var type: JsonValue = JsonValue.from("text") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(source: Source) = apply { + data = source.data + mediaType = source.mediaType + type = source.type + additionalProperties = + source.additionalProperties.toMutableMap() + } + + fun data(data: String) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] + * value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + fun mediaType(mediaType: String) = + mediaType(JsonField.of(mediaType)) + + /** + * Sets [Builder.mediaType] to an arbitrary JSON value. + * + * You should usually call [Builder.mediaType] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun mediaType(mediaType: JsonField) = apply { + this.mediaType = mediaType + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("text") + * ``` + * + * This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Source]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .data() + * .mediaType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Source = + Source( + checkRequired("data", data), + checkRequired("mediaType", mediaType), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Source = apply { + if (validated) { + return@apply + } + + data() + mediaType() + _type().let { + if (it != JsonValue.from("text")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (if (mediaType.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("text")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Source && + data == other.data && + mediaType == other.mediaType && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(data, mediaType, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Source{data=$data, mediaType=$mediaType, type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionDocumentObject && + citations == other.citations && + context == other.context && + source == other.source && + title == other.title && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + citations, + context, + source, + title, + type, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionDocumentObject{citations=$citations, context=$context, source=$source, title=$title, type=$type, additionalProperties=$additionalProperties}" + } + + class ChatCompletionVideoObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val videoUrl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of(), + @JsonProperty("video_url") + @ExcludeMissing + videoUrl: JsonField = JsonMissing.of(), + ) : this(type, videoUrl, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("video_url") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun videoUrl(): VideoUrl = videoUrl.getRequired("video_url") + + /** + * Returns the raw JSON value of [videoUrl]. + * + * Unlike [videoUrl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("video_url") + @ExcludeMissing + fun _videoUrl(): JsonField = videoUrl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionVideoObject]. + * + * The following fields are required: + * ```java + * .videoUrl() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionVideoObject]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("video_url") + private var videoUrl: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionVideoObject: ChatCompletionVideoObject + ) = apply { + type = chatCompletionVideoObject.type + videoUrl = chatCompletionVideoObject.videoUrl + additionalProperties = + chatCompletionVideoObject.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("video_url") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun videoUrl(videoUrl: VideoUrl) = videoUrl(JsonField.of(videoUrl)) + + /** + * Sets [Builder.videoUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.videoUrl] with a well-typed + * [VideoUrl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun videoUrl(videoUrl: JsonField) = apply { + this.videoUrl = videoUrl + } + + /** Alias for calling [videoUrl] with `VideoUrl.ofString(string)`. */ + fun videoUrl(string: String) = videoUrl(VideoUrl.ofString(string)) + + /** + * Alias for calling [videoUrl] with + * `VideoUrl.ofChatCompletionVideoUrlObject(chatCompletionVideoUrlObject)`. + */ + fun videoUrl( + chatCompletionVideoUrlObject: VideoUrl.ChatCompletionVideoUrlObject + ) = + videoUrl( + VideoUrl.ofChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject + ) + ) + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionVideoObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .videoUrl() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionVideoObject = + ChatCompletionVideoObject( + type, + checkRequired("videoUrl", videoUrl), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionVideoObject = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("video_url")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + videoUrl().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("video_url")) 1 else 0 } + + (videoUrl.asKnown().getOrNull()?.validity() ?: 0) + + @JsonDeserialize(using = VideoUrl.Deserializer::class) + @JsonSerialize(using = VideoUrl.Serializer::class) + class VideoUrl + private constructor( + private val string: String? = null, + private val chatCompletionVideoUrlObject: + ChatCompletionVideoUrlObject? = + null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun chatCompletionVideoUrlObject(): + Optional = + Optional.ofNullable(chatCompletionVideoUrlObject) + + fun isString(): Boolean = string != null + + fun isChatCompletionVideoUrlObject(): Boolean = + chatCompletionVideoUrlObject != null + + fun asString(): String = string.getOrThrow("string") + + fun asChatCompletionVideoUrlObject(): ChatCompletionVideoUrlObject = + chatCompletionVideoUrlObject.getOrThrow( + "chatCompletionVideoUrlObject" + ) + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + chatCompletionVideoUrlObject != null -> + visitor.visitChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): VideoUrl = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject: + ChatCompletionVideoUrlObject + ) { + chatCompletionVideoUrlObject.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject: + ChatCompletionVideoUrlObject + ) = chatCompletionVideoUrlObject.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is VideoUrl && + string == other.string && + chatCompletionVideoUrlObject == + other.chatCompletionVideoUrlObject + } + + override fun hashCode(): Int = + Objects.hash(string, chatCompletionVideoUrlObject) + + override fun toString(): String = + when { + string != null -> "VideoUrl{string=$string}" + chatCompletionVideoUrlObject != null -> + "VideoUrl{chatCompletionVideoUrlObject=$chatCompletionVideoUrlObject}" + _json != null -> "VideoUrl{_unknown=$_json}" + else -> throw IllegalStateException("Invalid VideoUrl") + } + + companion object { + + @JvmStatic fun ofString(string: String) = VideoUrl(string = string) + + @JvmStatic + fun ofChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject: ChatCompletionVideoUrlObject + ) = + VideoUrl( + chatCompletionVideoUrlObject = chatCompletionVideoUrlObject + ) + } + + /** + * An interface that defines how to map each variant of [VideoUrl] to a + * value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitChatCompletionVideoUrlObject( + chatCompletionVideoUrlObject: ChatCompletionVideoUrlObject + ): T + + /** + * Maps an unknown variant of [VideoUrl] to a value of type [T]. + * + * An instance of [VideoUrl] can contain an unknown variant if it + * was deserialized from data that doesn't match any known variant. + * For example, if the SDK is on an older version than the API, then + * the API may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown VideoUrl: $json") + } + } + + internal class Deserializer : + BaseDeserializer(VideoUrl::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): VideoUrl { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef< + ChatCompletionVideoUrlObject + >(), + ) + ?.let { + VideoUrl( + chatCompletionVideoUrlObject = it, + _json = json, + ) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { VideoUrl(string = it, _json = json) }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. + // deserializing from boolean). + 0 -> VideoUrl(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, + // then use the first completely valid match, or simply the + // first match if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } + ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(VideoUrl::class) { + + override fun serialize( + value: VideoUrl, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.chatCompletionVideoUrlObject != null -> + generator.writeObject( + value.chatCompletionVideoUrlObject + ) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid VideoUrl") + } + } + } + + class ChatCompletionVideoUrlObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val url: JsonField, + private val detail: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") + @ExcludeMissing + url: JsonField = JsonMissing.of(), + @JsonProperty("detail") + @ExcludeMissing + detail: JsonField = JsonMissing.of(), + ) : this(url, detail, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an + * unexpected type or is unexpectedly missing or null (e.g. if the + * server responded with an unexpected value). + */ + fun url(): String = url.getRequired("url") + + /** + * @throws HanzoInvalidDataException if the JSON field has an + * unexpected type (e.g. if the server responded with an + * unexpected value). + */ + fun detail(): Optional = detail.getOptional("detail") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("url") + @ExcludeMissing + fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [detail]. + * + * Unlike [detail], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("detail") + @ExcludeMissing + fun _detail(): JsonField = detail + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionVideoUrlObject]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionVideoUrlObject]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var detail: JsonField = JsonMissing.of() + private var additionalProperties: + MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionVideoUrlObject: ChatCompletionVideoUrlObject + ) = apply { + url = chatCompletionVideoUrlObject.url + detail = chatCompletionVideoUrlObject.detail + additionalProperties = + chatCompletionVideoUrlObject.additionalProperties + .toMutableMap() + } + + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed + * [String] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun detail(detail: String) = detail(JsonField.of(detail)) + + /** + * Sets [Builder.detail] to an arbitrary JSON value. + * + * You should usually call [Builder.detail] with a well-typed + * [String] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun detail(detail: JsonField) = apply { + this.detail = detail + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = + apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of + * [ChatCompletionVideoUrlObject]. + * + * Further updates to this [Builder] will not mutate the + * returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionVideoUrlObject = + ChatCompletionVideoUrlObject( + checkRequired("url", url), + detail, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionVideoUrlObject = apply { + if (validated) { + return@apply + } + + url() + detail() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (url.asKnown().isPresent) 1 else 0) + + (if (detail.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionVideoUrlObject && + url == other.url && + detail == other.detail && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(url, detail, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionVideoUrlObject{url=$url, detail=$detail, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionVideoObject && + type == other.type && + videoUrl == other.videoUrl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, videoUrl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionVideoObject{type=$type, videoUrl=$videoUrl, additionalProperties=$additionalProperties}" + } + + class ChatCompletionFileObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val file: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("file") + @ExcludeMissing + file: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + ) : this(file, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun file(): File = file.getRequired("file") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("file") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [file]. + * + * Unlike [file], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("file") @ExcludeMissing fun _file(): JsonField = file + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionFileObject]. + * + * The following fields are required: + * ```java + * .file() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionFileObject]. */ + class Builder internal constructor() { + + private var file: JsonField? = null + private var type: JsonValue = JsonValue.from("file") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionFileObject: ChatCompletionFileObject) = + apply { + file = chatCompletionFileObject.file + type = chatCompletionFileObject.type + additionalProperties = + chatCompletionFileObject.additionalProperties.toMutableMap() + } + + fun file(file: File) = file(JsonField.of(file)) + + /** + * Sets [Builder.file] to an arbitrary JSON value. + * + * You should usually call [Builder.file] with a well-typed [File] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun file(file: JsonField) = apply { this.file = file } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("file") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionFileObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .file() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionFileObject = + ChatCompletionFileObject( + checkRequired("file", file), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionFileObject = apply { + if (validated) { + return@apply + } + + file().validate() + _type().let { + if (it != JsonValue.from("file")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (file.asKnown().getOrNull()?.validity() ?: 0) + + type.let { if (it == JsonValue.from("file")) 1 else 0 } + + class File + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val fileData: JsonField, + private val fileId: JsonField, + private val filename: JsonField, + private val format: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("file_data") + @ExcludeMissing + fileData: JsonField = JsonMissing.of(), + @JsonProperty("file_id") + @ExcludeMissing + fileId: JsonField = JsonMissing.of(), + @JsonProperty("filename") + @ExcludeMissing + filename: JsonField = JsonMissing.of(), + @JsonProperty("format") + @ExcludeMissing + format: JsonField = JsonMissing.of(), + ) : this(fileData, fileId, filename, format, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun fileData(): Optional = fileData.getOptional("file_data") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun fileId(): Optional = fileId.getOptional("file_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun filename(): Optional = filename.getOptional("filename") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun format(): Optional = format.getOptional("format") + + /** + * Returns the raw JSON value of [fileData]. + * + * Unlike [fileData], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("file_data") + @ExcludeMissing + fun _fileData(): JsonField = fileData + + /** + * Returns the raw JSON value of [fileId]. + * + * Unlike [fileId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("file_id") + @ExcludeMissing + fun _fileId(): JsonField = fileId + + /** + * Returns the raw JSON value of [filename]. + * + * Unlike [filename], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("filename") + @ExcludeMissing + fun _filename(): JsonField = filename + + /** + * Returns the raw JSON value of [format]. + * + * Unlike [format], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("format") + @ExcludeMissing + fun _format(): JsonField = format + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [File]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [File]. */ + class Builder internal constructor() { + + private var fileData: JsonField = JsonMissing.of() + private var fileId: JsonField = JsonMissing.of() + private var filename: JsonField = JsonMissing.of() + private var format: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(file: File) = apply { + fileData = file.fileData + fileId = file.fileId + filename = file.filename + format = file.format + additionalProperties = file.additionalProperties.toMutableMap() + } + + fun fileData(fileData: String) = fileData(JsonField.of(fileData)) + + /** + * Sets [Builder.fileData] to an arbitrary JSON value. + * + * You should usually call [Builder.fileData] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun fileData(fileData: JsonField) = apply { + this.fileData = fileData + } + + fun fileId(fileId: String) = fileId(JsonField.of(fileId)) + + /** + * Sets [Builder.fileId] to an arbitrary JSON value. + * + * You should usually call [Builder.fileId] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun fileId(fileId: JsonField) = apply { + this.fileId = fileId + } + + fun filename(filename: String) = filename(JsonField.of(filename)) + + /** + * Sets [Builder.filename] to an arbitrary JSON value. + * + * You should usually call [Builder.filename] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun filename(filename: JsonField) = apply { + this.filename = filename + } + + fun format(format: String) = format(JsonField.of(format)) + + /** + * Sets [Builder.format] to an arbitrary JSON value. + * + * You should usually call [Builder.format] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun format(format: JsonField) = apply { + this.format = format + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [File]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): File = + File( + fileData, + fileId, + filename, + format, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): File = apply { + if (validated) { + return@apply + } + + fileData() + fileId() + filename() + format() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (fileData.asKnown().isPresent) 1 else 0) + + (if (fileId.asKnown().isPresent) 1 else 0) + + (if (filename.asKnown().isPresent) 1 else 0) + + (if (format.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is File && + fileData == other.fileData && + fileId == other.fileId && + filename == other.filename && + format == other.format && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + fileData, + fileId, + filename, + format, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "File{fileData=$fileData, fileId=$fileId, filename=$filename, format=$format, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionFileObject && + file == other.file && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(file, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionFileObject{file=$file, type=$type, additionalProperties=$additionalProperties}" + } + } + } + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CacheControl]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionUserMessage && + content == other.content && + role == other.role && + cacheControl == other.cacheControl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(content, role, cacheControl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionUserMessage{content=$content, role=$role, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" + } + + class ChatCompletionAssistantMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val role: JsonValue, + private val cacheControl: JsonField, + private val content: JsonField, + private val functionCall: JsonField, + private val name: JsonField, + private val reasoningContent: JsonField, + private val thinkingBlocks: JsonField>, + private val toolCalls: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("function_call") + @ExcludeMissing + functionCall: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("reasoning_content") + @ExcludeMissing + reasoningContent: JsonField = JsonMissing.of(), + @JsonProperty("thinking_blocks") + @ExcludeMissing + thinkingBlocks: JsonField> = JsonMissing.of(), + @JsonProperty("tool_calls") + @ExcludeMissing + toolCalls: JsonField> = JsonMissing.of(), + ) : this( + role, + cacheControl, + content, + functionCall, + name, + reasoningContent, + thinkingBlocks, + toolCalls, + mutableMapOf(), + ) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("assistant") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun cacheControl(): Optional = cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun functionCall(): Optional = functionCall.getOptional("function_call") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun reasoningContent(): Optional = + reasoningContent.getOptional("reasoning_content") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun thinkingBlocks(): Optional> = + thinkingBlocks.getOptional("thinking_blocks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun toolCalls(): Optional> = toolCalls.getOptional("tool_calls") + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [functionCall]. + * + * Unlike [functionCall], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_call") + @ExcludeMissing + fun _functionCall(): JsonField = functionCall + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [reasoningContent]. + * + * Unlike [reasoningContent], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("reasoning_content") + @ExcludeMissing + fun _reasoningContent(): JsonField = reasoningContent + + /** + * Returns the raw JSON value of [thinkingBlocks]. + * + * Unlike [thinkingBlocks], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("thinking_blocks") + @ExcludeMissing + fun _thinkingBlocks(): JsonField> = thinkingBlocks + + /** + * Returns the raw JSON value of [toolCalls]. + * + * Unlike [toolCalls], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tool_calls") + @ExcludeMissing + fun _toolCalls(): JsonField> = toolCalls + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionAssistantMessage]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionAssistantMessage]. */ + class Builder internal constructor() { + + private var role: JsonValue = JsonValue.from("assistant") + private var cacheControl: JsonField = JsonMissing.of() + private var content: JsonField = JsonMissing.of() + private var functionCall: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var reasoningContent: JsonField = JsonMissing.of() + private var thinkingBlocks: JsonField>? = null + private var toolCalls: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionAssistantMessage: ChatCompletionAssistantMessage) = + apply { + role = chatCompletionAssistantMessage.role + cacheControl = chatCompletionAssistantMessage.cacheControl + content = chatCompletionAssistantMessage.content + functionCall = chatCompletionAssistantMessage.functionCall + name = chatCompletionAssistantMessage.name + reasoningContent = chatCompletionAssistantMessage.reasoningContent + thinkingBlocks = + chatCompletionAssistantMessage.thinkingBlocks.map { it.toMutableList() } + toolCalls = + chatCompletionAssistantMessage.toolCalls.map { it.toMutableList() } + additionalProperties = + chatCompletionAssistantMessage.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("assistant") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed [CacheControl] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun content(content: Content?) = content(JsonField.ofNullable(content)) + + /** Alias for calling [Builder.content] with `content.orElse(null)`. */ + fun content(content: Optional) = content(content.getOrNull()) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** + * Alias for calling [content] with + * `Content.ofUnnamedSchemaWithArrayParent3s(unnamedSchemaWithArrayParent3s)`. + */ + fun contentOfUnnamedSchemaWithArrayParent3s( + unnamedSchemaWithArrayParent3s: List + ) = + content( + Content.ofUnnamedSchemaWithArrayParent3s(unnamedSchemaWithArrayParent3s) + ) + + fun functionCall(functionCall: FunctionCall?) = + functionCall(JsonField.ofNullable(functionCall)) + + /** Alias for calling [Builder.functionCall] with `functionCall.orElse(null)`. */ + fun functionCall(functionCall: Optional) = + functionCall(functionCall.getOrNull()) + + /** + * Sets [Builder.functionCall] to an arbitrary JSON value. + * + * You should usually call [Builder.functionCall] with a well-typed [FunctionCall] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun functionCall(functionCall: JsonField) = apply { + this.functionCall = functionCall + } + + fun name(name: String?) = name(JsonField.ofNullable(name)) + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun reasoningContent(reasoningContent: String?) = + reasoningContent(JsonField.ofNullable(reasoningContent)) + + /** + * Alias for calling [Builder.reasoningContent] with + * `reasoningContent.orElse(null)`. + */ + fun reasoningContent(reasoningContent: Optional) = + reasoningContent(reasoningContent.getOrNull()) + + /** + * Sets [Builder.reasoningContent] to an arbitrary JSON value. + * + * You should usually call [Builder.reasoningContent] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun reasoningContent(reasoningContent: JsonField) = apply { + this.reasoningContent = reasoningContent + } + + fun thinkingBlocks(thinkingBlocks: List?) = + thinkingBlocks(JsonField.ofNullable(thinkingBlocks)) + + /** + * Alias for calling [Builder.thinkingBlocks] with `thinkingBlocks.orElse(null)`. + */ + fun thinkingBlocks(thinkingBlocks: Optional>) = + thinkingBlocks(thinkingBlocks.getOrNull()) + + /** + * Sets [Builder.thinkingBlocks] to an arbitrary JSON value. + * + * You should usually call [Builder.thinkingBlocks] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun thinkingBlocks(thinkingBlocks: JsonField>) = apply { + this.thinkingBlocks = thinkingBlocks.map { it.toMutableList() } + } + + /** + * Adds a single [ThinkingBlock] to [thinkingBlocks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addThinkingBlock(thinkingBlock: ThinkingBlock) = apply { + thinkingBlocks = + (thinkingBlocks ?: JsonField.of(mutableListOf())).also { + checkKnown("thinkingBlocks", it).add(thinkingBlock) + } + } + + /** + * Alias for calling [addThinkingBlock] with + * `ThinkingBlock.ofChatCompletion(chatCompletion)`. + */ + fun addThinkingBlock(chatCompletion: ThinkingBlock.ChatCompletionThinkingBlock) = + addThinkingBlock(ThinkingBlock.ofChatCompletion(chatCompletion)) + + /** + * Alias for calling [addThinkingBlock] with + * `ThinkingBlock.ofChatCompletionRedacted(chatCompletionRedacted)`. + */ + fun addThinkingBlock( + chatCompletionRedacted: ThinkingBlock.ChatCompletionRedactedThinkingBlock + ) = addThinkingBlock(ThinkingBlock.ofChatCompletionRedacted(chatCompletionRedacted)) + + fun toolCalls(toolCalls: List?) = + toolCalls(JsonField.ofNullable(toolCalls)) + + /** Alias for calling [Builder.toolCalls] with `toolCalls.orElse(null)`. */ + fun toolCalls(toolCalls: Optional>) = + toolCalls(toolCalls.getOrNull()) + + /** + * Sets [Builder.toolCalls] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCalls] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun toolCalls(toolCalls: JsonField>) = apply { + this.toolCalls = toolCalls.map { it.toMutableList() } + } + + /** + * Adds a single [ToolCall] to [toolCalls]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addToolCall(toolCall: ToolCall) = apply { + toolCalls = + (toolCalls ?: JsonField.of(mutableListOf())).also { + checkKnown("toolCalls", it).add(toolCall) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionAssistantMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ChatCompletionAssistantMessage = + ChatCompletionAssistantMessage( + role, + cacheControl, + content, + functionCall, + name, + reasoningContent, + (thinkingBlocks ?: JsonMissing.of()).map { it.toImmutable() }, + (toolCalls ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionAssistantMessage = apply { + if (validated) { + return@apply + } + + _role().let { + if (it != JsonValue.from("assistant")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + content().ifPresent { it.validate() } + functionCall().ifPresent { it.validate() } + name() + reasoningContent() + thinkingBlocks().ifPresent { it.forEach { it.validate() } } + toolCalls().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + role.let { if (it == JsonValue.from("assistant")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (content.asKnown().getOrNull()?.validity() ?: 0) + + (functionCall.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (reasoningContent.asKnown().isPresent) 1 else 0) + + (thinkingBlocks.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (toolCalls.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CacheControl]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val unnamedSchemaWithArrayParent3s: List? = + null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun unnamedSchemaWithArrayParent3s(): + Optional> = + Optional.ofNullable(unnamedSchemaWithArrayParent3s) + + fun isString(): Boolean = string != null + + fun isUnnamedSchemaWithArrayParent3s(): Boolean = + unnamedSchemaWithArrayParent3s != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnnamedSchemaWithArrayParent3s(): List = + unnamedSchemaWithArrayParent3s.getOrThrow("unnamedSchemaWithArrayParent3s") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + unnamedSchemaWithArrayParent3s != null -> + visitor.visitUnnamedSchemaWithArrayParent3s( + unnamedSchemaWithArrayParent3s + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitUnnamedSchemaWithArrayParent3s( + unnamedSchemaWithArrayParent3s: List + ) { + unnamedSchemaWithArrayParent3s.forEach { it.validate() } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitUnnamedSchemaWithArrayParent3s( + unnamedSchemaWithArrayParent3s: List + ) = unnamedSchemaWithArrayParent3s.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + unnamedSchemaWithArrayParent3s == other.unnamedSchemaWithArrayParent3s + } + + override fun hashCode(): Int = Objects.hash(string, unnamedSchemaWithArrayParent3s) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + unnamedSchemaWithArrayParent3s != null -> + "Content{unnamedSchemaWithArrayParent3s=$unnamedSchemaWithArrayParent3s}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofUnnamedSchemaWithArrayParent3s( + unnamedSchemaWithArrayParent3s: List + ) = + Content( + unnamedSchemaWithArrayParent3s = + unnamedSchemaWithArrayParent3s.toImmutable() + ) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitUnnamedSchemaWithArrayParent3s( + unnamedSchemaWithArrayParent3s: List + ): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { + Content( + unnamedSchemaWithArrayParent3s = it, + _json = json, + ) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unnamedSchemaWithArrayParent3s != null -> + generator.writeObject(value.unnamedSchemaWithArrayParent3s) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + + @JsonDeserialize(using = UnnamedSchemaWithArrayParent3.Deserializer::class) + @JsonSerialize(using = UnnamedSchemaWithArrayParent3.Serializer::class) + class UnnamedSchemaWithArrayParent3 + private constructor( + private val chatCompletionTextObject: ChatCompletionTextObject? = null, + private val chatCompletionThinkingBlock: ChatCompletionThinkingBlock? = null, + private val _json: JsonValue? = null, + ) { + + fun chatCompletionTextObject(): Optional = + Optional.ofNullable(chatCompletionTextObject) + + fun chatCompletionThinkingBlock(): Optional = + Optional.ofNullable(chatCompletionThinkingBlock) + + fun isChatCompletionTextObject(): Boolean = chatCompletionTextObject != null + + fun isChatCompletionThinkingBlock(): Boolean = + chatCompletionThinkingBlock != null + + fun asChatCompletionTextObject(): ChatCompletionTextObject = + chatCompletionTextObject.getOrThrow("chatCompletionTextObject") + + fun asChatCompletionThinkingBlock(): ChatCompletionThinkingBlock = + chatCompletionThinkingBlock.getOrThrow("chatCompletionThinkingBlock") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + chatCompletionTextObject != null -> + visitor.visitChatCompletionTextObject(chatCompletionTextObject) + chatCompletionThinkingBlock != null -> + visitor.visitChatCompletionThinkingBlock( + chatCompletionThinkingBlock + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): UnnamedSchemaWithArrayParent3 = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) { + chatCompletionTextObject.validate() + } + + override fun visitChatCompletionThinkingBlock( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ) { + chatCompletionThinkingBlock.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) = chatCompletionTextObject.validity() + + override fun visitChatCompletionThinkingBlock( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ) = chatCompletionThinkingBlock.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnnamedSchemaWithArrayParent3 && + chatCompletionTextObject == other.chatCompletionTextObject && + chatCompletionThinkingBlock == other.chatCompletionThinkingBlock + } + + override fun hashCode(): Int = + Objects.hash(chatCompletionTextObject, chatCompletionThinkingBlock) + + override fun toString(): String = + when { + chatCompletionTextObject != null -> + "UnnamedSchemaWithArrayParent3{chatCompletionTextObject=$chatCompletionTextObject}" + chatCompletionThinkingBlock != null -> + "UnnamedSchemaWithArrayParent3{chatCompletionThinkingBlock=$chatCompletionThinkingBlock}" + _json != null -> "UnnamedSchemaWithArrayParent3{_unknown=$_json}" + else -> + throw IllegalStateException("Invalid UnnamedSchemaWithArrayParent3") + } + + companion object { + + @JvmStatic + fun ofChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ) = + UnnamedSchemaWithArrayParent3( + chatCompletionTextObject = chatCompletionTextObject + ) + + @JvmStatic + fun ofChatCompletionThinkingBlock( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ) = + UnnamedSchemaWithArrayParent3( + chatCompletionThinkingBlock = chatCompletionThinkingBlock + ) + } + + /** + * An interface that defines how to map each variant of + * [UnnamedSchemaWithArrayParent3] to a value of type [T]. + */ + interface Visitor { + + fun visitChatCompletionTextObject( + chatCompletionTextObject: ChatCompletionTextObject + ): T + + fun visitChatCompletionThinkingBlock( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ): T + + /** + * Maps an unknown variant of [UnnamedSchemaWithArrayParent3] to a value of + * type [T]. + * + * An instance of [UnnamedSchemaWithArrayParent3] can contain an unknown + * variant if it was deserialized from data that doesn't match any known + * variant. For example, if the SDK is on an older version than the API, + * then the API may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException( + "Unknown UnnamedSchemaWithArrayParent3: $json" + ) + } + } + + internal class Deserializer : + BaseDeserializer( + UnnamedSchemaWithArrayParent3::class + ) { + + override fun ObjectCodec.deserialize( + node: JsonNode + ): UnnamedSchemaWithArrayParent3 { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent3( + chatCompletionTextObject = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + UnnamedSchemaWithArrayParent3( + chatCompletionThinkingBlock = it, + _json = json, + ) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing + // from boolean). + 0 -> UnnamedSchemaWithArrayParent3(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then + // use the first completely valid match, or simply the first match + // if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer( + UnnamedSchemaWithArrayParent3::class + ) { + + override fun serialize( + value: UnnamedSchemaWithArrayParent3, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.chatCompletionTextObject != null -> + generator.writeObject(value.chatCompletionTextObject) + value.chatCompletionThinkingBlock != null -> + generator.writeObject(value.chatCompletionThinkingBlock) + value._json != null -> generator.writeObject(value._json) + else -> + throw IllegalStateException( + "Invalid UnnamedSchemaWithArrayParent3" + ) + } + } + } + + class ChatCompletionTextObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val text: JsonField, + private val type: JsonValue, + private val cacheControl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("text") + @ExcludeMissing + text: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + ) : this(text, type, cacheControl, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun text(): String = text.getRequired("text") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("text") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * Returns the raw JSON value of [text]. + * + * Unlike [text], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("text") @ExcludeMissing fun _text(): JsonField = text + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionTextObject]. + * + * The following fields are required: + * ```java + * .text() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionTextObject]. */ + class Builder internal constructor() { + + private var text: JsonField? = null + private var type: JsonValue = JsonValue.from("text") + private var cacheControl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionTextObject: ChatCompletionTextObject) = + apply { + text = chatCompletionTextObject.text + type = chatCompletionTextObject.type + cacheControl = chatCompletionTextObject.cacheControl + additionalProperties = + chatCompletionTextObject.additionalProperties.toMutableMap() + } + + fun text(text: String) = text(JsonField.of(text)) + + /** + * Sets [Builder.text] to an arbitrary JSON value. + * + * You should usually call [Builder.text] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun text(text: JsonField) = apply { this.text = text } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("text") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionTextObject]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .text() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionTextObject = + ChatCompletionTextObject( + checkRequired("text", text), + type, + cacheControl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionTextObject = apply { + if (validated) { + return@apply + } + + text() + _type().let { + if (it != JsonValue.from("text")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + cacheControl().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (text.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("text")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if + * the server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [CacheControl]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = + cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionTextObject && + text == other.text && + type == other.type && + cacheControl == other.cacheControl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(text, type, cacheControl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionTextObject{text=$text, type=$type, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" + } + + class ChatCompletionThinkingBlock + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val cacheControl: JsonField, + private val signature: JsonField, + private val thinking: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") + @ExcludeMissing + type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("signature") + @ExcludeMissing + signature: JsonField = JsonMissing.of(), + @JsonProperty("thinking") + @ExcludeMissing + thinking: JsonField = JsonMissing.of(), + ) : this(type, cacheControl, signature, thinking, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("thinking") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun signature(): Optional = signature.getOptional("signature") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun thinking(): Optional = thinking.getOptional("thinking") + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [signature]. + * + * Unlike [signature], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("signature") + @ExcludeMissing + fun _signature(): JsonField = signature + + /** + * Returns the raw JSON value of [thinking]. + * + * Unlike [thinking], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("thinking") + @ExcludeMissing + fun _thinking(): JsonField = thinking + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionThinkingBlock]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionThinkingBlock]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("thinking") + private var cacheControl: JsonField = JsonMissing.of() + private var signature: JsonField = JsonMissing.of() + private var thinking: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ) = apply { + type = chatCompletionThinkingBlock.type + cacheControl = chatCompletionThinkingBlock.cacheControl + signature = chatCompletionThinkingBlock.signature + thinking = chatCompletionThinkingBlock.thinking + additionalProperties = + chatCompletionThinkingBlock.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("thinking") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl?) = + cacheControl(JsonField.ofNullable(cacheControl)) + + /** + * Alias for calling [Builder.cacheControl] with + * `cacheControl.orElse(null)`. + */ + fun cacheControl(cacheControl: Optional) = + cacheControl(cacheControl.getOrNull()) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofUnionMember0(unionMember0)`. + */ + fun cacheControl(unionMember0: CacheControl.UnionMember0) = + cacheControl(CacheControl.ofUnionMember0(unionMember0)) + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofChatCompletionCachedContent()`. + */ + fun cacheControlChatCompletionCachedContent() = + cacheControl(CacheControl.ofChatCompletionCachedContent()) + + fun signature(signature: String) = signature(JsonField.of(signature)) + + /** + * Sets [Builder.signature] to an arbitrary JSON value. + * + * You should usually call [Builder.signature] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun signature(signature: JsonField) = apply { + this.signature = signature + } + + fun thinking(thinking: String) = thinking(JsonField.of(thinking)) + + /** + * Sets [Builder.thinking] to an arbitrary JSON value. + * + * You should usually call [Builder.thinking] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun thinking(thinking: JsonField) = apply { + this.thinking = thinking + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionThinkingBlock]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): ChatCompletionThinkingBlock = + ChatCompletionThinkingBlock( + type, + cacheControl, + signature, + thinking, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionThinkingBlock = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("thinking")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + cacheControl().ifPresent { it.validate() } + signature() + thinking() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("thinking")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (if (signature.asKnown().isPresent) 1 else 0) + + (if (thinking.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = CacheControl.Deserializer::class) + @JsonSerialize(using = CacheControl.Serializer::class) + class CacheControl + private constructor( + private val unionMember0: UnionMember0? = null, + private val chatCompletionCachedContent: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun unionMember0(): Optional = + Optional.ofNullable(unionMember0) + + fun chatCompletionCachedContent(): Optional = + Optional.ofNullable(chatCompletionCachedContent) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isChatCompletionCachedContent(): Boolean = + chatCompletionCachedContent != null + + fun asUnionMember0(): UnionMember0 = + unionMember0.getOrThrow("unionMember0") + + fun asChatCompletionCachedContent(): JsonValue = + chatCompletionCachedContent.getOrThrow( + "chatCompletionCachedContent" + ) + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + unionMember0 != null -> visitor.visitUnionMember0(unionMember0) + chatCompletionCachedContent != null -> + visitor.visitChatCompletionCachedContent( + chatCompletionCachedContent + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) { + unionMember0.validate() + } + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) { + chatCompletionCachedContent.let { + if ( + it != + JsonValue.from(mapOf("type" to "ephemeral")) + ) { + throw HanzoInvalidDataException( + "'chatCompletionCachedContent' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) = + unionMember0.validity() + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) = + chatCompletionCachedContent.let { + if ( + it == + JsonValue.from(mapOf("type" to "ephemeral")) + ) + 1 + else 0 + } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + unionMember0 == other.unionMember0 && + chatCompletionCachedContent == other.chatCompletionCachedContent + } + + override fun hashCode(): Int = + Objects.hash(unionMember0, chatCompletionCachedContent) + + override fun toString(): String = + when { + unionMember0 != null -> + "CacheControl{unionMember0=$unionMember0}" + chatCompletionCachedContent != null -> + "CacheControl{chatCompletionCachedContent=$chatCompletionCachedContent}" + _json != null -> "CacheControl{_unknown=$_json}" + else -> throw IllegalStateException("Invalid CacheControl") + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + CacheControl(unionMember0 = unionMember0) + + @JvmStatic + fun ofChatCompletionCachedContent() = + CacheControl( + chatCompletionCachedContent = + JsonValue.from(mapOf("type" to "ephemeral")) + ) + } + + /** + * An interface that defines how to map each variant of [CacheControl] + * to a value of type [T]. + */ + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ): T + + /** + * Maps an unknown variant of [CacheControl] to a value of type [T]. + * + * An instance of [CacheControl] can contain an unknown variant if + * it was deserialized from data that doesn't match any known + * variant. For example, if the SDK is on an older version than the + * API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown CacheControl: $json") + } + } + + internal class Deserializer : + BaseDeserializer(CacheControl::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): CacheControl { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl( + chatCompletionCachedContent = it, + _json = json, + ) + } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl( + unionMember0 = it, + _json = json, + ) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. + // deserializing from boolean). + 0 -> CacheControl(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, + // then use the first completely valid match, or simply the + // first match if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } + ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer(CacheControl::class) { + + override fun serialize( + value: CacheControl, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.unionMember0 != null -> + generator.writeObject(value.unionMember0) + value.chatCompletionCachedContent != null -> + generator.writeObject(value.chatCompletionCachedContent) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid CacheControl") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UnionMember0]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember0]. */ + class Builder internal constructor() { + + private var additionalProperties: + MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember0: UnionMember0) = apply { + additionalProperties = + unionMember0.additionalProperties.toMutableMap() + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = + apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember0]. + * + * Further updates to this [Builder] will not mutate the + * returned instance. + */ + fun build(): UnionMember0 = + UnionMember0(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember0 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember0 && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UnionMember0{additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionThinkingBlock && + type == other.type && + cacheControl == other.cacheControl && + signature == other.signature && + thinking == other.thinking && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + type, + cacheControl, + signature, + thinking, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionThinkingBlock{type=$type, cacheControl=$cacheControl, signature=$signature, thinking=$thinking, additionalProperties=$additionalProperties}" + } + } + } + + class FunctionCall + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val arguments: JsonField, + private val name: JsonField, + private val providerSpecificFields: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("arguments") + @ExcludeMissing + arguments: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("provider_specific_fields") + @ExcludeMissing + providerSpecificFields: JsonField = JsonMissing.of(), + ) : this(arguments, name, providerSpecificFields, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun arguments(): Optional = arguments.getOptional("arguments") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun providerSpecificFields(): Optional = + providerSpecificFields.getOptional("provider_specific_fields") + + /** + * Returns the raw JSON value of [arguments]. + * + * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("arguments") + @ExcludeMissing + fun _arguments(): JsonField = arguments + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [providerSpecificFields]. + * + * Unlike [providerSpecificFields], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("provider_specific_fields") + @ExcludeMissing + fun _providerSpecificFields(): JsonField = + providerSpecificFields + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FunctionCall]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionCall]. */ + class Builder internal constructor() { + + private var arguments: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var providerSpecificFields: JsonField = + JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(functionCall: FunctionCall) = apply { + arguments = functionCall.arguments + name = functionCall.name + providerSpecificFields = functionCall.providerSpecificFields + additionalProperties = functionCall.additionalProperties.toMutableMap() + } + + fun arguments(arguments: String) = arguments(JsonField.of(arguments)) + + /** + * Sets [Builder.arguments] to an arbitrary JSON value. + * + * You should usually call [Builder.arguments] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun arguments(arguments: JsonField) = apply { + this.arguments = arguments + } + + fun name(name: String?) = name(JsonField.ofNullable(name)) + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun providerSpecificFields(providerSpecificFields: ProviderSpecificFields?) = + providerSpecificFields(JsonField.ofNullable(providerSpecificFields)) + + /** + * Alias for calling [Builder.providerSpecificFields] with + * `providerSpecificFields.orElse(null)`. + */ + fun providerSpecificFields( + providerSpecificFields: Optional + ) = providerSpecificFields(providerSpecificFields.getOrNull()) + + /** + * Sets [Builder.providerSpecificFields] to an arbitrary JSON value. + * + * You should usually call [Builder.providerSpecificFields] with a well-typed + * [ProviderSpecificFields] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun providerSpecificFields( + providerSpecificFields: JsonField + ) = apply { this.providerSpecificFields = providerSpecificFields } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FunctionCall]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FunctionCall = + FunctionCall( + arguments, + name, + providerSpecificFields, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): FunctionCall = apply { + if (validated) { + return@apply + } + + arguments() + name() + providerSpecificFields().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (arguments.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (providerSpecificFields.asKnown().getOrNull()?.validity() ?: 0) + + class ProviderSpecificFields + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ProviderSpecificFields]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProviderSpecificFields]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(providerSpecificFields: ProviderSpecificFields) = apply { + additionalProperties = + providerSpecificFields.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProviderSpecificFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProviderSpecificFields = + ProviderSpecificFields(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ProviderSpecificFields = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProviderSpecificFields && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProviderSpecificFields{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FunctionCall && + arguments == other.arguments && + name == other.name && + providerSpecificFields == other.providerSpecificFields && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(arguments, name, providerSpecificFields, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FunctionCall{arguments=$arguments, name=$name, providerSpecificFields=$providerSpecificFields, additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = ThinkingBlock.Deserializer::class) + @JsonSerialize(using = ThinkingBlock.Serializer::class) + class ThinkingBlock + private constructor( + private val chatCompletion: ChatCompletionThinkingBlock? = null, + private val chatCompletionRedacted: ChatCompletionRedactedThinkingBlock? = null, + private val _json: JsonValue? = null, + ) { + + fun chatCompletion(): Optional = + Optional.ofNullable(chatCompletion) + + fun chatCompletionRedacted(): Optional = + Optional.ofNullable(chatCompletionRedacted) + + fun isChatCompletion(): Boolean = chatCompletion != null + + fun isChatCompletionRedacted(): Boolean = chatCompletionRedacted != null + + fun asChatCompletion(): ChatCompletionThinkingBlock = + chatCompletion.getOrThrow("chatCompletion") + + fun asChatCompletionRedacted(): ChatCompletionRedactedThinkingBlock = + chatCompletionRedacted.getOrThrow("chatCompletionRedacted") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + chatCompletion != null -> visitor.visitChatCompletion(chatCompletion) + chatCompletionRedacted != null -> + visitor.visitChatCompletionRedacted(chatCompletionRedacted) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): ThinkingBlock = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitChatCompletion( + chatCompletion: ChatCompletionThinkingBlock + ) { + chatCompletion.validate() + } + + override fun visitChatCompletionRedacted( + chatCompletionRedacted: ChatCompletionRedactedThinkingBlock + ) { + chatCompletionRedacted.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitChatCompletion( + chatCompletion: ChatCompletionThinkingBlock + ) = chatCompletion.validity() + + override fun visitChatCompletionRedacted( + chatCompletionRedacted: ChatCompletionRedactedThinkingBlock + ) = chatCompletionRedacted.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ThinkingBlock && + chatCompletion == other.chatCompletion && + chatCompletionRedacted == other.chatCompletionRedacted + } + + override fun hashCode(): Int = Objects.hash(chatCompletion, chatCompletionRedacted) + + override fun toString(): String = + when { + chatCompletion != null -> "ThinkingBlock{chatCompletion=$chatCompletion}" + chatCompletionRedacted != null -> + "ThinkingBlock{chatCompletionRedacted=$chatCompletionRedacted}" + _json != null -> "ThinkingBlock{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ThinkingBlock") + } + + companion object { + + @JvmStatic + fun ofChatCompletion(chatCompletion: ChatCompletionThinkingBlock) = + ThinkingBlock(chatCompletion = chatCompletion) + + @JvmStatic + fun ofChatCompletionRedacted( + chatCompletionRedacted: ChatCompletionRedactedThinkingBlock + ) = ThinkingBlock(chatCompletionRedacted = chatCompletionRedacted) + } + + /** + * An interface that defines how to map each variant of [ThinkingBlock] to a value + * of type [T]. + */ + interface Visitor { + + fun visitChatCompletion(chatCompletion: ChatCompletionThinkingBlock): T + + fun visitChatCompletionRedacted( + chatCompletionRedacted: ChatCompletionRedactedThinkingBlock + ): T + + /** + * Maps an unknown variant of [ThinkingBlock] to a value of type [T]. + * + * An instance of [ThinkingBlock] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown ThinkingBlock: $json") + } + } + + internal class Deserializer : + BaseDeserializer(ThinkingBlock::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): ThinkingBlock { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { ThinkingBlock(chatCompletion = it, _json = json) }, + tryDeserialize( + node, + jacksonTypeRef(), + ) + ?.let { + ThinkingBlock(chatCompletionRedacted = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> ThinkingBlock(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(ThinkingBlock::class) { + + override fun serialize( + value: ThinkingBlock, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.chatCompletion != null -> + generator.writeObject(value.chatCompletion) + value.chatCompletionRedacted != null -> + generator.writeObject(value.chatCompletionRedacted) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid ThinkingBlock") + } + } + } + + class ChatCompletionThinkingBlock + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val cacheControl: JsonField, + private val signature: JsonField, + private val thinking: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("signature") + @ExcludeMissing + signature: JsonField = JsonMissing.of(), + @JsonProperty("thinking") + @ExcludeMissing + thinking: JsonField = JsonMissing.of(), + ) : this(type, cacheControl, signature, thinking, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("thinking") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun signature(): Optional = signature.getOptional("signature") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun thinking(): Optional = thinking.getOptional("thinking") + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [signature]. + * + * Unlike [signature], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("signature") + @ExcludeMissing + fun _signature(): JsonField = signature + + /** + * Returns the raw JSON value of [thinking]. + * + * Unlike [thinking], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("thinking") + @ExcludeMissing + fun _thinking(): JsonField = thinking + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionThinkingBlock]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionThinkingBlock]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("thinking") + private var cacheControl: JsonField = JsonMissing.of() + private var signature: JsonField = JsonMissing.of() + private var thinking: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionThinkingBlock: ChatCompletionThinkingBlock + ) = apply { + type = chatCompletionThinkingBlock.type + cacheControl = chatCompletionThinkingBlock.cacheControl + signature = chatCompletionThinkingBlock.signature + thinking = chatCompletionThinkingBlock.thinking + additionalProperties = + chatCompletionThinkingBlock.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults + * to the following: + * ```java + * JsonValue.from("thinking") + * ``` + * + * This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl?) = + cacheControl(JsonField.ofNullable(cacheControl)) + + /** + * Alias for calling [Builder.cacheControl] with + * `cacheControl.orElse(null)`. + */ + fun cacheControl(cacheControl: Optional) = + cacheControl(cacheControl.getOrNull()) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofUnionMember0(unionMember0)`. + */ + fun cacheControl(unionMember0: CacheControl.UnionMember0) = + cacheControl(CacheControl.ofUnionMember0(unionMember0)) + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofChatCompletionCachedContent()`. + */ + fun cacheControlChatCompletionCachedContent() = + cacheControl(CacheControl.ofChatCompletionCachedContent()) + + fun signature(signature: String) = signature(JsonField.of(signature)) + + /** + * Sets [Builder.signature] to an arbitrary JSON value. + * + * You should usually call [Builder.signature] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun signature(signature: JsonField) = apply { + this.signature = signature + } + + fun thinking(thinking: String) = thinking(JsonField.of(thinking)) + + /** + * Sets [Builder.thinking] to an arbitrary JSON value. + * + * You should usually call [Builder.thinking] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun thinking(thinking: JsonField) = apply { + this.thinking = thinking + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionThinkingBlock]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ChatCompletionThinkingBlock = + ChatCompletionThinkingBlock( + type, + cacheControl, + signature, + thinking, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionThinkingBlock = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("thinking")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + signature() + thinking() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("thinking")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (if (signature.asKnown().isPresent) 1 else 0) + + (if (thinking.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = CacheControl.Deserializer::class) + @JsonSerialize(using = CacheControl.Serializer::class) + class CacheControl + private constructor( + private val unionMember0: UnionMember0? = null, + private val chatCompletionCachedContent: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun unionMember0(): Optional = + Optional.ofNullable(unionMember0) + + fun chatCompletionCachedContent(): Optional = + Optional.ofNullable(chatCompletionCachedContent) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isChatCompletionCachedContent(): Boolean = + chatCompletionCachedContent != null + + fun asUnionMember0(): UnionMember0 = unionMember0.getOrThrow("unionMember0") + + fun asChatCompletionCachedContent(): JsonValue = + chatCompletionCachedContent.getOrThrow("chatCompletionCachedContent") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + unionMember0 != null -> visitor.visitUnionMember0(unionMember0) + chatCompletionCachedContent != null -> + visitor.visitChatCompletionCachedContent( + chatCompletionCachedContent + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) { + unionMember0.validate() + } + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) { + chatCompletionCachedContent.let { + if ( + it != JsonValue.from(mapOf("type" to "ephemeral")) + ) { + throw HanzoInvalidDataException( + "'chatCompletionCachedContent' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) = + unionMember0.validity() + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) = + chatCompletionCachedContent.let { + if (it == JsonValue.from(mapOf("type" to "ephemeral"))) + 1 + else 0 + } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + unionMember0 == other.unionMember0 && + chatCompletionCachedContent == other.chatCompletionCachedContent + } + + override fun hashCode(): Int = + Objects.hash(unionMember0, chatCompletionCachedContent) + + override fun toString(): String = + when { + unionMember0 != null -> "CacheControl{unionMember0=$unionMember0}" + chatCompletionCachedContent != null -> + "CacheControl{chatCompletionCachedContent=$chatCompletionCachedContent}" + _json != null -> "CacheControl{_unknown=$_json}" + else -> throw IllegalStateException("Invalid CacheControl") + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + CacheControl(unionMember0 = unionMember0) + + @JvmStatic + fun ofChatCompletionCachedContent() = + CacheControl( + chatCompletionCachedContent = + JsonValue.from(mapOf("type" to "ephemeral")) + ) + } + + /** + * An interface that defines how to map each variant of [CacheControl] to a + * value of type [T]. + */ + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ): T + + /** + * Maps an unknown variant of [CacheControl] to a value of type [T]. + * + * An instance of [CacheControl] can contain an unknown variant if it + * was deserialized from data that doesn't match any known variant. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown CacheControl: $json") + } + } + + internal class Deserializer : + BaseDeserializer(CacheControl::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): CacheControl { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl( + chatCompletionCachedContent = it, + _json = json, + ) + } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl(unionMember0 = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. + // deserializing from boolean). + 0 -> CacheControl(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, + // then use the first completely valid match, or simply the + // first match if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } + ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer(CacheControl::class) { + + override fun serialize( + value: CacheControl, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.unionMember0 != null -> + generator.writeObject(value.unionMember0) + value.chatCompletionCachedContent != null -> + generator.writeObject(value.chatCompletionCachedContent) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid CacheControl") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UnionMember0]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember0]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember0: UnionMember0) = apply { + additionalProperties = + unionMember0.additionalProperties.toMutableMap() + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember0]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): UnionMember0 = + UnionMember0(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember0 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember0 && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UnionMember0{additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionThinkingBlock && + type == other.type && + cacheControl == other.cacheControl && + signature == other.signature && + thinking == other.thinking && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, cacheControl, signature, thinking, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionThinkingBlock{type=$type, cacheControl=$cacheControl, signature=$signature, thinking=$thinking, additionalProperties=$additionalProperties}" + } + + class ChatCompletionRedactedThinkingBlock + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val cacheControl: JsonField, + private val data: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("data") + @ExcludeMissing + data: JsonField = JsonMissing.of(), + ) : this(type, cacheControl, data, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("redacted_thinking") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionRedactedThinkingBlock]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionRedactedThinkingBlock]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("redacted_thinking") + private var cacheControl: JsonField = JsonMissing.of() + private var data: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from( + chatCompletionRedactedThinkingBlock: ChatCompletionRedactedThinkingBlock + ) = apply { + type = chatCompletionRedactedThinkingBlock.type + cacheControl = chatCompletionRedactedThinkingBlock.cacheControl + data = chatCompletionRedactedThinkingBlock.data + additionalProperties = + chatCompletionRedactedThinkingBlock.additionalProperties + .toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults + * to the following: + * ```java + * JsonValue.from("redacted_thinking") + * ``` + * + * This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl?) = + cacheControl(JsonField.ofNullable(cacheControl)) + + /** + * Alias for calling [Builder.cacheControl] with + * `cacheControl.orElse(null)`. + */ + fun cacheControl(cacheControl: Optional) = + cacheControl(cacheControl.getOrNull()) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofUnionMember0(unionMember0)`. + */ + fun cacheControl(unionMember0: CacheControl.UnionMember0) = + cacheControl(CacheControl.ofUnionMember0(unionMember0)) + + /** + * Alias for calling [cacheControl] with + * `CacheControl.ofChatCompletionCachedContent()`. + */ + fun cacheControlChatCompletionCachedContent() = + cacheControl(CacheControl.ofChatCompletionCachedContent()) + + fun data(data: String) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun data(data: JsonField) = apply { this.data = data } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionRedactedThinkingBlock]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ChatCompletionRedactedThinkingBlock = + ChatCompletionRedactedThinkingBlock( + type, + cacheControl, + data, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionRedactedThinkingBlock = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("redacted_thinking")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + data() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("redacted_thinking")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (if (data.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = CacheControl.Deserializer::class) + @JsonSerialize(using = CacheControl.Serializer::class) + class CacheControl + private constructor( + private val unionMember0: UnionMember0? = null, + private val chatCompletionCachedContent: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun unionMember0(): Optional = + Optional.ofNullable(unionMember0) + + fun chatCompletionCachedContent(): Optional = + Optional.ofNullable(chatCompletionCachedContent) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isChatCompletionCachedContent(): Boolean = + chatCompletionCachedContent != null + + fun asUnionMember0(): UnionMember0 = unionMember0.getOrThrow("unionMember0") + + fun asChatCompletionCachedContent(): JsonValue = + chatCompletionCachedContent.getOrThrow("chatCompletionCachedContent") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + unionMember0 != null -> visitor.visitUnionMember0(unionMember0) + chatCompletionCachedContent != null -> + visitor.visitChatCompletionCachedContent( + chatCompletionCachedContent + ) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) { + unionMember0.validate() + } + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) { + chatCompletionCachedContent.let { + if ( + it != JsonValue.from(mapOf("type" to "ephemeral")) + ) { + throw HanzoInvalidDataException( + "'chatCompletionCachedContent' is invalid, received $it" + ) + } + } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) = + unionMember0.validity() + + override fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ) = + chatCompletionCachedContent.let { + if (it == JsonValue.from(mapOf("type" to "ephemeral"))) + 1 + else 0 + } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + unionMember0 == other.unionMember0 && + chatCompletionCachedContent == other.chatCompletionCachedContent + } + + override fun hashCode(): Int = + Objects.hash(unionMember0, chatCompletionCachedContent) + + override fun toString(): String = + when { + unionMember0 != null -> "CacheControl{unionMember0=$unionMember0}" + chatCompletionCachedContent != null -> + "CacheControl{chatCompletionCachedContent=$chatCompletionCachedContent}" + _json != null -> "CacheControl{_unknown=$_json}" + else -> throw IllegalStateException("Invalid CacheControl") + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + CacheControl(unionMember0 = unionMember0) + + @JvmStatic + fun ofChatCompletionCachedContent() = + CacheControl( + chatCompletionCachedContent = + JsonValue.from(mapOf("type" to "ephemeral")) + ) + } + + /** + * An interface that defines how to map each variant of [CacheControl] to a + * value of type [T]. + */ + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitChatCompletionCachedContent( + chatCompletionCachedContent: JsonValue + ): T + + /** + * Maps an unknown variant of [CacheControl] to a value of type [T]. + * + * An instance of [CacheControl] can contain an unknown variant if it + * was deserialized from data that doesn't match any known variant. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown CacheControl: $json") + } + } + + internal class Deserializer : + BaseDeserializer(CacheControl::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): CacheControl { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl( + chatCompletionCachedContent = it, + _json = json, + ) + } + ?.takeIf { it.isValid() }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { + CacheControl(unionMember0 = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. + // deserializing from boolean). + 0 -> CacheControl(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, + // then use the first completely valid match, or simply the + // first match if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } + ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer(CacheControl::class) { + + override fun serialize( + value: CacheControl, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.unionMember0 != null -> + generator.writeObject(value.unionMember0) + value.chatCompletionCachedContent != null -> + generator.writeObject(value.chatCompletionCachedContent) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid CacheControl") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UnionMember0]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember0]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember0: UnionMember0) = apply { + additionalProperties = + unionMember0.additionalProperties.toMutableMap() + } + + fun additionalProperties( + additionalProperties: Map + ) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember0]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): UnionMember0 = + UnionMember0(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember0 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember0 && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UnionMember0{additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionRedactedThinkingBlock && + type == other.type && + cacheControl == other.cacheControl && + data == other.data && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, cacheControl, data, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionRedactedThinkingBlock{type=$type, cacheControl=$cacheControl, data=$data, additionalProperties=$additionalProperties}" + } + } + + class ToolCall + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val id: JsonField, + private val function: JsonField, + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("function") + @ExcludeMissing + function: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + ) : this(id, function, type, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun function(): Function = function.getRequired("function") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("function") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [function]. + * + * Unlike [function], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function") + @ExcludeMissing + fun _function(): JsonField = function + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ToolCall]. + * + * The following fields are required: + * ```java + * .id() + * .function() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ToolCall]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var function: JsonField? = null + private var type: JsonValue = JsonValue.from("function") + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(toolCall: ToolCall) = apply { + id = toolCall.id + function = toolCall.function + type = toolCall.type + additionalProperties = toolCall.additionalProperties.toMutableMap() + } + + fun id(id: String?) = id(JsonField.ofNullable(id)) + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + fun function(function: Function) = function(JsonField.of(function)) + + /** + * Sets [Builder.function] to an arbitrary JSON value. + * + * You should usually call [Builder.function] with a well-typed [Function] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun function(function: JsonField) = apply { this.function = function } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("function") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ToolCall]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .function() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ToolCall = + ToolCall( + checkRequired("id", id), + checkRequired("function", function), + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ToolCall = apply { + if (validated) { + return@apply + } + + id() + function().validate() + _type().let { + if (it != JsonValue.from("function")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (function.asKnown().getOrNull()?.validity() ?: 0) + + type.let { if (it == JsonValue.from("function")) 1 else 0 } + + class Function + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val arguments: JsonField, + private val name: JsonField, + private val providerSpecificFields: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("arguments") + @ExcludeMissing + arguments: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("provider_specific_fields") + @ExcludeMissing + providerSpecificFields: JsonField = JsonMissing.of(), + ) : this(arguments, name, providerSpecificFields, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun arguments(): Optional = arguments.getOptional("arguments") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun providerSpecificFields(): Optional = + providerSpecificFields.getOptional("provider_specific_fields") + + /** + * Returns the raw JSON value of [arguments]. + * + * Unlike [arguments], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("arguments") + @ExcludeMissing + fun _arguments(): JsonField = arguments + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [providerSpecificFields]. + * + * Unlike [providerSpecificFields], this method doesn't throw if the JSON field + * has an unexpected type. + */ + @JsonProperty("provider_specific_fields") + @ExcludeMissing + fun _providerSpecificFields(): JsonField = + providerSpecificFields + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Function]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var arguments: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var providerSpecificFields: JsonField = + JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + arguments = function.arguments + name = function.name + providerSpecificFields = function.providerSpecificFields + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun arguments(arguments: String) = arguments(JsonField.of(arguments)) + + /** + * Sets [Builder.arguments] to an arbitrary JSON value. + * + * You should usually call [Builder.arguments] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun arguments(arguments: JsonField) = apply { + this.arguments = arguments + } + + fun name(name: String?) = name(JsonField.ofNullable(name)) + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun providerSpecificFields( + providerSpecificFields: ProviderSpecificFields? + ) = providerSpecificFields(JsonField.ofNullable(providerSpecificFields)) + + /** + * Alias for calling [Builder.providerSpecificFields] with + * `providerSpecificFields.orElse(null)`. + */ + fun providerSpecificFields( + providerSpecificFields: Optional + ) = providerSpecificFields(providerSpecificFields.getOrNull()) + + /** + * Sets [Builder.providerSpecificFields] to an arbitrary JSON value. + * + * You should usually call [Builder.providerSpecificFields] with a + * well-typed [ProviderSpecificFields] value instead. This method is + * primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun providerSpecificFields( + providerSpecificFields: JsonField + ) = apply { this.providerSpecificFields = providerSpecificFields } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Function = + Function( + arguments, + name, + providerSpecificFields, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + arguments() + name() + providerSpecificFields().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (arguments.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (providerSpecificFields.asKnown().getOrNull()?.validity() ?: 0) + + class ProviderSpecificFields + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ProviderSpecificFields]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProviderSpecificFields]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(providerSpecificFields: ProviderSpecificFields) = + apply { + additionalProperties = + providerSpecificFields.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProviderSpecificFields]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): ProviderSpecificFields = + ProviderSpecificFields(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ProviderSpecificFields = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProviderSpecificFields && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProviderSpecificFields{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Function && + arguments == other.arguments && + name == other.name && + providerSpecificFields == other.providerSpecificFields && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(arguments, name, providerSpecificFields, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{arguments=$arguments, name=$name, providerSpecificFields=$providerSpecificFields, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ToolCall && + id == other.id && + function == other.function && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, function, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ToolCall{id=$id, function=$function, type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionAssistantMessage && + role == other.role && + cacheControl == other.cacheControl && + content == other.content && + functionCall == other.functionCall && + name == other.name && + reasoningContent == other.reasoningContent && + thinkingBlocks == other.thinkingBlocks && + toolCalls == other.toolCalls && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + role, + cacheControl, + content, + functionCall, + name, + reasoningContent, + thinkingBlocks, + toolCalls, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionAssistantMessage{role=$role, cacheControl=$cacheControl, content=$content, functionCall=$functionCall, name=$name, reasoningContent=$reasoningContent, thinkingBlocks=$thinkingBlocks, toolCalls=$toolCalls, additionalProperties=$additionalProperties}" + } + + class ChatCompletionToolMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val content: JsonField, + private val role: JsonValue, + private val toolCallId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("tool_call_id") + @ExcludeMissing + toolCallId: JsonField = JsonMissing.of(), + ) : this(content, role, toolCallId, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun content(): Content = content.getRequired("content") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("tool") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun toolCallId(): String = toolCallId.getRequired("tool_call_id") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [toolCallId]. + * + * Unlike [toolCallId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tool_call_id") + @ExcludeMissing + fun _toolCallId(): JsonField = toolCallId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionToolMessage]. + * + * The following fields are required: + * ```java + * .content() + * .toolCallId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionToolMessage]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var role: JsonValue = JsonValue.from("tool") + private var toolCallId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionToolMessage: ChatCompletionToolMessage) = apply { + content = chatCompletionToolMessage.content + role = chatCompletionToolMessage.role + toolCallId = chatCompletionToolMessage.toolCallId + additionalProperties = + chatCompletionToolMessage.additionalProperties.toMutableMap() + } + + fun content(content: Content) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** + * Alias for calling [content] with + * `Content.ofChatCompletionTextObjects(chatCompletionTextObjects)`. + */ + fun contentOfChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = content(Content.ofChatCompletionTextObjects(chatCompletionTextObjects)) + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("tool") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun toolCallId(toolCallId: String) = toolCallId(JsonField.of(toolCallId)) + + /** + * Sets [Builder.toolCallId] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCallId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun toolCallId(toolCallId: JsonField) = apply { + this.toolCallId = toolCallId + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionToolMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * .toolCallId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionToolMessage = + ChatCompletionToolMessage( + checkRequired("content", content), + role, + checkRequired("toolCallId", toolCallId), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionToolMessage = apply { + if (validated) { + return@apply + } + + content().validate() + _role().let { + if (it != JsonValue.from("tool")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + toolCallId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (content.asKnown().getOrNull()?.validity() ?: 0) + + role.let { if (it == JsonValue.from("tool")) 1 else 0 } + + (if (toolCallId.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val chatCompletionTextObjects: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun chatCompletionTextObjects(): Optional> = + Optional.ofNullable(chatCompletionTextObjects) + + fun isString(): Boolean = string != null + + fun isChatCompletionTextObjects(): Boolean = chatCompletionTextObjects != null + + fun asString(): String = string.getOrThrow("string") + + fun asChatCompletionTextObjects(): List = + chatCompletionTextObjects.getOrThrow("chatCompletionTextObjects") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + chatCompletionTextObjects != null -> + visitor.visitChatCompletionTextObjects(chatCompletionTextObjects) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ) { + chatCompletionTextObjects.forEach { it.validate() } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = chatCompletionTextObjects.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + chatCompletionTextObjects == other.chatCompletionTextObjects + } + + override fun hashCode(): Int = Objects.hash(string, chatCompletionTextObjects) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + chatCompletionTextObjects != null -> + "Content{chatCompletionTextObjects=$chatCompletionTextObjects}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = Content(chatCompletionTextObjects = chatCompletionTextObjects.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { + Content(chatCompletionTextObjects = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.chatCompletionTextObjects != null -> + generator.writeObject(value.chatCompletionTextObjects) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + + class ChatCompletionTextObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val text: JsonField, + private val type: JsonValue, + private val cacheControl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("text") + @ExcludeMissing + text: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + ) : this(text, type, cacheControl, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun text(): String = text.getRequired("text") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("text") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * Returns the raw JSON value of [text]. + * + * Unlike [text], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("text") @ExcludeMissing fun _text(): JsonField = text + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionTextObject]. + * + * The following fields are required: + * ```java + * .text() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionTextObject]. */ + class Builder internal constructor() { + + private var text: JsonField? = null + private var type: JsonValue = JsonValue.from("text") + private var cacheControl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionTextObject: ChatCompletionTextObject) = + apply { + text = chatCompletionTextObject.text + type = chatCompletionTextObject.type + cacheControl = chatCompletionTextObject.cacheControl + additionalProperties = + chatCompletionTextObject.additionalProperties.toMutableMap() + } + + fun text(text: String) = text(JsonField.of(text)) + + /** + * Sets [Builder.text] to an arbitrary JSON value. + * + * You should usually call [Builder.text] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun text(text: JsonField) = apply { this.text = text } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults + * to the following: + * ```java + * JsonValue.from("text") + * ``` + * + * This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionTextObject]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .text() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionTextObject = + ChatCompletionTextObject( + checkRequired("text", text), + type, + cacheControl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionTextObject = apply { + if (validated) { + return@apply + } + + text() + _type().let { + if (it != JsonValue.from("text")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (text.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("text")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [CacheControl]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = + cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionTextObject && + text == other.text && + type == other.type && + cacheControl == other.cacheControl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(text, type, cacheControl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionTextObject{text=$text, type=$type, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionToolMessage && + content == other.content && + role == other.role && + toolCallId == other.toolCallId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(content, role, toolCallId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionToolMessage{content=$content, role=$role, toolCallId=$toolCallId, additionalProperties=$additionalProperties}" + } + + class ChatCompletionSystemMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val content: JsonField, + private val role: JsonValue, + private val cacheControl: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(content, role, cacheControl, name, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun content(): Content = content.getRequired("content") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("system") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun cacheControl(): Optional = cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionSystemMessage]. + * + * The following fields are required: + * ```java + * .content() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionSystemMessage]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var role: JsonValue = JsonValue.from("system") + private var cacheControl: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionSystemMessage: ChatCompletionSystemMessage) = + apply { + content = chatCompletionSystemMessage.content + role = chatCompletionSystemMessage.role + cacheControl = chatCompletionSystemMessage.cacheControl + name = chatCompletionSystemMessage.name + additionalProperties = + chatCompletionSystemMessage.additionalProperties.toMutableMap() + } + + fun content(content: Content) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** Alias for calling [content] with `Content.ofJsonValues(jsonValues)`. */ + fun contentOfJsonValues(jsonValues: List) = + content(Content.ofJsonValues(jsonValues)) + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("system") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed [CacheControl] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionSystemMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionSystemMessage = + ChatCompletionSystemMessage( + checkRequired("content", content), + role, + cacheControl, + name, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionSystemMessage = apply { + if (validated) { + return@apply + } + + content().validate() + _role().let { + if (it != JsonValue.from("system")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (content.asKnown().getOrNull()?.validity() ?: 0) + + role.let { if (it == JsonValue.from("system")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val jsonValues: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun jsonValues(): Optional> = Optional.ofNullable(jsonValues) + + fun isString(): Boolean = string != null + + fun isJsonValues(): Boolean = jsonValues != null + + fun asString(): String = string.getOrThrow("string") + + fun asJsonValues(): List = jsonValues.getOrThrow("jsonValues") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + jsonValues != null -> visitor.visitJsonValues(jsonValues) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitJsonValues(jsonValues: List) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitJsonValues(jsonValues: List) = + jsonValues.size + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + jsonValues == other.jsonValues + } + + override fun hashCode(): Int = Objects.hash(string, jsonValues) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + jsonValues != null -> "Content{jsonValues=$jsonValues}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofJsonValues(jsonValues: List) = + Content(jsonValues = jsonValues.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitJsonValues(jsonValues: List): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Content(jsonValues = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.jsonValues != null -> generator.writeObject(value.jsonValues) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + } + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CacheControl]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionSystemMessage && + content == other.content && + role == other.role && + cacheControl == other.cacheControl && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(content, role, cacheControl, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionSystemMessage{content=$content, role=$role, cacheControl=$cacheControl, name=$name, additionalProperties=$additionalProperties}" + } + + class ChatCompletionFunctionMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val content: JsonField, + private val name: JsonField, + private val role: JsonValue, + private val toolCallId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("tool_call_id") + @ExcludeMissing + toolCallId: JsonField = JsonMissing.of(), + ) : this(content, name, role, toolCallId, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun name(): String = name.getRequired("name") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("function") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun toolCallId(): Optional = toolCallId.getOptional("tool_call_id") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [toolCallId]. + * + * Unlike [toolCallId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tool_call_id") + @ExcludeMissing + fun _toolCallId(): JsonField = toolCallId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionFunctionMessage]. + * + * The following fields are required: + * ```java + * .content() + * .name() + * .toolCallId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionFunctionMessage]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var name: JsonField? = null + private var role: JsonValue = JsonValue.from("function") + private var toolCallId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionFunctionMessage: ChatCompletionFunctionMessage) = + apply { + content = chatCompletionFunctionMessage.content + name = chatCompletionFunctionMessage.name + role = chatCompletionFunctionMessage.role + toolCallId = chatCompletionFunctionMessage.toolCallId + additionalProperties = + chatCompletionFunctionMessage.additionalProperties.toMutableMap() + } + + fun content(content: Content?) = content(JsonField.ofNullable(content)) + + /** Alias for calling [Builder.content] with `content.orElse(null)`. */ + fun content(content: Optional) = content(content.getOrNull()) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** + * Alias for calling [content] with + * `Content.ofChatCompletionTextObjects(chatCompletionTextObjects)`. + */ + fun contentOfChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = content(Content.ofChatCompletionTextObjects(chatCompletionTextObjects)) + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("function") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun toolCallId(toolCallId: String?) = toolCallId(JsonField.ofNullable(toolCallId)) + + /** Alias for calling [Builder.toolCallId] with `toolCallId.orElse(null)`. */ + fun toolCallId(toolCallId: Optional) = toolCallId(toolCallId.getOrNull()) + + /** + * Sets [Builder.toolCallId] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCallId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun toolCallId(toolCallId: JsonField) = apply { + this.toolCallId = toolCallId + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionFunctionMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * .name() + * .toolCallId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionFunctionMessage = + ChatCompletionFunctionMessage( + checkRequired("content", content), + checkRequired("name", name), + role, + checkRequired("toolCallId", toolCallId), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionFunctionMessage = apply { + if (validated) { + return@apply + } + + content().ifPresent { it.validate() } + name() + _role().let { + if (it != JsonValue.from("function")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + toolCallId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (content.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + role.let { if (it == JsonValue.from("function")) 1 else 0 } + + (if (toolCallId.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val chatCompletionTextObjects: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun chatCompletionTextObjects(): Optional> = + Optional.ofNullable(chatCompletionTextObjects) + + fun isString(): Boolean = string != null + + fun isChatCompletionTextObjects(): Boolean = chatCompletionTextObjects != null + + fun asString(): String = string.getOrThrow("string") + + fun asChatCompletionTextObjects(): List = + chatCompletionTextObjects.getOrThrow("chatCompletionTextObjects") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + chatCompletionTextObjects != null -> + visitor.visitChatCompletionTextObjects(chatCompletionTextObjects) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ) { + chatCompletionTextObjects.forEach { it.validate() } + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = chatCompletionTextObjects.sumOf { it.validity().toInt() } + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + chatCompletionTextObjects == other.chatCompletionTextObjects + } + + override fun hashCode(): Int = Objects.hash(string, chatCompletionTextObjects) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + chatCompletionTextObjects != null -> + "Content{chatCompletionTextObjects=$chatCompletionTextObjects}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofChatCompletionTextObjects( + chatCompletionTextObjects: List + ) = Content(chatCompletionTextObjects = chatCompletionTextObjects.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitChatCompletionTextObjects( + chatCompletionTextObjects: List + ): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize( + node, + jacksonTypeRef>(), + ) + ?.let { + Content(chatCompletionTextObjects = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.chatCompletionTextObjects != null -> + generator.writeObject(value.chatCompletionTextObjects) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + + class ChatCompletionTextObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val text: JsonField, + private val type: JsonValue, + private val cacheControl: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("text") + @ExcludeMissing + text: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + ) : this(text, type, cacheControl, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ + fun text(): String = text.getRequired("text") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("text") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun cacheControl(): Optional = + cacheControl.getOptional("cache_control") + + /** + * Returns the raw JSON value of [text]. + * + * Unlike [text], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("text") @ExcludeMissing fun _text(): JsonField = text + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionTextObject]. + * + * The following fields are required: + * ```java + * .text() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionTextObject]. */ + class Builder internal constructor() { + + private var text: JsonField? = null + private var type: JsonValue = JsonValue.from("text") + private var cacheControl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionTextObject: ChatCompletionTextObject) = + apply { + text = chatCompletionTextObject.text + type = chatCompletionTextObject.type + cacheControl = chatCompletionTextObject.cacheControl + additionalProperties = + chatCompletionTextObject.additionalProperties.toMutableMap() + } + + fun text(text: String) = text(JsonField.of(text)) + + /** + * Sets [Builder.text] to an arbitrary JSON value. + * + * You should usually call [Builder.text] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun text(text: JsonField) = apply { this.text = text } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults + * to the following: + * ```java + * JsonValue.from("text") + * ``` + * + * This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed + * [CacheControl] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionTextObject]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .text() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionTextObject = + ChatCompletionTextObject( + checkRequired("text", text), + type, + cacheControl, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionTextObject = apply { + if (validated) { + return@apply + } + + text() + _type().let { + if (it != JsonValue.from("text")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (text.asKnown().isPresent) 1 else 0) + + type.let { if (it == JsonValue.from("text")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the + * server responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [CacheControl]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = + cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field + * defaults to the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException( + "'type' is invalid, received $it" + ) + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionTextObject && + text == other.text && + type == other.type && + cacheControl == other.cacheControl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(text, type, cacheControl, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionTextObject{text=$text, type=$type, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionFunctionMessage && + content == other.content && + name == other.name && + role == other.role && + toolCallId == other.toolCallId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(content, name, role, toolCallId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionFunctionMessage{content=$content, name=$name, role=$role, toolCallId=$toolCallId, additionalProperties=$additionalProperties}" + } + + class ChatCompletionDeveloperMessage + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val content: JsonField, + private val role: JsonValue, + private val cacheControl: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("content") + @ExcludeMissing + content: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(), + @JsonProperty("cache_control") + @ExcludeMissing + cacheControl: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(content, role, cacheControl, name, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun content(): Content = content.getRequired("content") + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("developer") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun cacheControl(): Optional = cacheControl.getOptional("cache_control") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [cacheControl]. + * + * Unlike [cacheControl], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cache_control") + @ExcludeMissing + fun _cacheControl(): JsonField = cacheControl + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionDeveloperMessage]. + * + * The following fields are required: + * ```java + * .content() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionDeveloperMessage]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var role: JsonValue = JsonValue.from("developer") + private var cacheControl: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionDeveloperMessage: ChatCompletionDeveloperMessage) = + apply { + content = chatCompletionDeveloperMessage.content + role = chatCompletionDeveloperMessage.role + cacheControl = chatCompletionDeveloperMessage.cacheControl + name = chatCompletionDeveloperMessage.name + additionalProperties = + chatCompletionDeveloperMessage.additionalProperties.toMutableMap() + } + + fun content(content: Content) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofString(string)`. */ + fun content(string: String) = content(Content.ofString(string)) + + /** Alias for calling [content] with `Content.ofJsonValues(jsonValues)`. */ + fun contentOfJsonValues(jsonValues: List) = + content(Content.ofJsonValues(jsonValues)) + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to the + * following: + * ```java + * JsonValue.from("developer") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonValue) = apply { this.role = role } + + fun cacheControl(cacheControl: CacheControl) = + cacheControl(JsonField.of(cacheControl)) + + /** + * Sets [Builder.cacheControl] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheControl] with a well-typed [CacheControl] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionDeveloperMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionDeveloperMessage = + ChatCompletionDeveloperMessage( + checkRequired("content", content), + role, + cacheControl, + name, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionDeveloperMessage = apply { + if (validated) { + return@apply + } + + content().validate() + _role().let { + if (it != JsonValue.from("developer")) { + throw HanzoInvalidDataException("'role' is invalid, received $it") + } + } + cacheControl().ifPresent { it.validate() } + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (content.asKnown().getOrNull()?.validity() ?: 0) + + role.let { if (it == JsonValue.from("developer")) 1 else 0 } + + (cacheControl.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val string: String? = null, + private val jsonValues: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun jsonValues(): Optional> = Optional.ofNullable(jsonValues) + + fun isString(): Boolean = string != null + + fun isJsonValues(): Boolean = jsonValues != null + + fun asString(): String = string.getOrThrow("string") + + fun asJsonValues(): List = jsonValues.getOrThrow("jsonValues") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + jsonValues != null -> visitor.visitJsonValues(jsonValues) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitJsonValues(jsonValues: List) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitJsonValues(jsonValues: List) = + jsonValues.size + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Content && + string == other.string && + jsonValues == other.jsonValues + } + + override fun hashCode(): Int = Objects.hash(string, jsonValues) + + override fun toString(): String = + when { + string != null -> "Content{string=$string}" + jsonValues != null -> "Content{jsonValues=$jsonValues}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Content(string = string) + + @JvmStatic + fun ofJsonValues(jsonValues: List) = + Content(jsonValues = jsonValues.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitJsonValues(jsonValues: List): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Content(jsonValues = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Content(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.jsonValues != null -> generator.writeObject(value.jsonValues) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + } + + class CacheControl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * Expected to always return the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * However, this method can be useful for debugging and logging (e.g. if the server + * responded with an unexpected value). + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CacheControl]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CacheControl]. */ + class Builder internal constructor() { + + private var type: JsonValue = JsonValue.from("ephemeral") + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(cacheControl: CacheControl) = apply { + type = cacheControl.type + additionalProperties = cacheControl.additionalProperties.toMutableMap() + } + + /** + * Sets the field to an arbitrary JSON value. + * + * It is usually unnecessary to call this method because the field defaults to + * the following: + * ```java + * JsonValue.from("ephemeral") + * ``` + * + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonValue) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CacheControl]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CacheControl = + CacheControl(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CacheControl = apply { + if (validated) { + return@apply + } + + _type().let { + if (it != JsonValue.from("ephemeral")) { + throw HanzoInvalidDataException("'type' is invalid, received $it") + } + } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + type.let { if (it == JsonValue.from("ephemeral")) 1 else 0 } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CacheControl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CacheControl{type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionDeveloperMessage && + content == other.content && + role == other.role && + cacheControl == other.cacheControl && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(content, role, cacheControl, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionDeveloperMessage{content=$content, role=$role, cacheControl=$cacheControl, name=$name, additionalProperties=$additionalProperties}" + } + } + + class ContextWindowFallbackDict + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ContextWindowFallbackDict]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ContextWindowFallbackDict]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(contextWindowFallbackDict: ContextWindowFallbackDict) = apply { + additionalProperties = contextWindowFallbackDict.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ContextWindowFallbackDict]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ContextWindowFallbackDict = + ContextWindowFallbackDict(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ContextWindowFallbackDict = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ContextWindowFallbackDict && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ContextWindowFallbackDict{additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = FunctionCall.Deserializer::class) + @JsonSerialize(using = FunctionCall.Serializer::class) + class FunctionCall + private constructor( + private val string: String? = null, + private val unionMember1: UnionMember1? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun unionMember1(): Optional = Optional.ofNullable(unionMember1) + + fun isString(): Boolean = string != null + + fun isUnionMember1(): Boolean = unionMember1 != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnionMember1(): UnionMember1 = unionMember1.getOrThrow("unionMember1") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + unionMember1 != null -> visitor.visitUnionMember1(unionMember1) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): FunctionCall = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitUnionMember1(unionMember1: UnionMember1) { + unionMember1.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitUnionMember1(unionMember1: UnionMember1) = + unionMember1.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FunctionCall && + string == other.string && + unionMember1 == other.unionMember1 + } + + override fun hashCode(): Int = Objects.hash(string, unionMember1) + + override fun toString(): String = + when { + string != null -> "FunctionCall{string=$string}" + unionMember1 != null -> "FunctionCall{unionMember1=$unionMember1}" + _json != null -> "FunctionCall{_unknown=$_json}" + else -> throw IllegalStateException("Invalid FunctionCall") + } + + companion object { + + @JvmStatic fun ofString(string: String) = FunctionCall(string = string) + + @JvmStatic + fun ofUnionMember1(unionMember1: UnionMember1) = + FunctionCall(unionMember1 = unionMember1) + } + + /** + * An interface that defines how to map each variant of [FunctionCall] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitUnionMember1(unionMember1: UnionMember1): T + + /** + * Maps an unknown variant of [FunctionCall] to a value of type [T]. + * + * An instance of [FunctionCall] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown FunctionCall: $json") + } + } + + internal class Deserializer : BaseDeserializer(FunctionCall::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): FunctionCall { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionCall(unionMember1 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionCall(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> FunctionCall(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(FunctionCall::class) { + + override fun serialize( + value: FunctionCall, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unionMember1 != null -> generator.writeObject(value.unionMember1) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid FunctionCall") + } + } + } + + class UnionMember1 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UnionMember1]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember1]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember1: UnionMember1) = apply { + additionalProperties = unionMember1.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember1]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UnionMember1 = UnionMember1(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember1 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember1 && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "UnionMember1{additionalProperties=$additionalProperties}" + } + } + + class Function + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Function]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Function = Function(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Function && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Function{additionalProperties=$additionalProperties}" + } + + class LogitBias + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [LogitBias]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LogitBias]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(logitBias: LogitBias) = apply { + additionalProperties = logitBias.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [LogitBias]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): LogitBias = LogitBias(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): LogitBias = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is LogitBias && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "LogitBias{additionalProperties=$additionalProperties}" + } + + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + class ResponseFormat + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ResponseFormat]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseFormat]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseFormat: ResponseFormat) = apply { + additionalProperties = responseFormat.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ResponseFormat]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseFormat = ResponseFormat(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ResponseFormat = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ResponseFormat && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseFormat{additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = Stop.Deserializer::class) + @JsonSerialize(using = Stop.Serializer::class) + class Stop + private constructor( + private val string: String? = null, + private val strings: List? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Stop = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitStrings(strings: List) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitStrings(strings: List) = strings.size + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Stop && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Stop{string=$string}" + strings != null -> "Stop{strings=$strings}" + _json != null -> "Stop{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Stop") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Stop(string = string) + + @JvmStatic fun ofStrings(strings: List) = Stop(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Stop] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + + /** + * Maps an unknown variant of [Stop] to a value of type [T]. + * + * An instance of [Stop] can contain an unknown variant if it was deserialized from data + * that doesn't match any known variant. For example, if the SDK is on an older version + * than the API, then the API may respond with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Stop: $json") + } + } + + internal class Deserializer : BaseDeserializer(Stop::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Stop { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Stop(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Stop(strings = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> Stop(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Stop::class) { + + override fun serialize( + value: Stop, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.strings != null -> generator.writeObject(value.strings) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Stop") + } + } + } + } + + class StreamOptions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [StreamOptions]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [StreamOptions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(streamOptions: StreamOptions) = apply { + additionalProperties = streamOptions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [StreamOptions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): StreamOptions = StreamOptions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): StreamOptions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is StreamOptions && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "StreamOptions{additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = ToolChoice.Deserializer::class) + @JsonSerialize(using = ToolChoice.Serializer::class) + class ToolChoice + private constructor( + private val string: String? = null, + private val unionMember1: UnionMember1? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun unionMember1(): Optional = Optional.ofNullable(unionMember1) + + fun isString(): Boolean = string != null + + fun isUnionMember1(): Boolean = unionMember1 != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnionMember1(): UnionMember1 = unionMember1.getOrThrow("unionMember1") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + unionMember1 != null -> visitor.visitUnionMember1(unionMember1) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): ToolChoice = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitUnionMember1(unionMember1: UnionMember1) { + unionMember1.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitUnionMember1(unionMember1: UnionMember1) = + unionMember1.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ToolChoice && + string == other.string && + unionMember1 == other.unionMember1 + } + + override fun hashCode(): Int = Objects.hash(string, unionMember1) + + override fun toString(): String = + when { + string != null -> "ToolChoice{string=$string}" + unionMember1 != null -> "ToolChoice{unionMember1=$unionMember1}" + _json != null -> "ToolChoice{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ToolChoice") + } + + companion object { + + @JvmStatic fun ofString(string: String) = ToolChoice(string = string) + + @JvmStatic + fun ofUnionMember1(unionMember1: UnionMember1) = ToolChoice(unionMember1 = unionMember1) + } + + /** + * An interface that defines how to map each variant of [ToolChoice] to a value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitUnionMember1(unionMember1: UnionMember1): T + + /** + * Maps an unknown variant of [ToolChoice] to a value of type [T]. + * + * An instance of [ToolChoice] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the SDK + * is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown ToolChoice: $json") + } + } + + internal class Deserializer : BaseDeserializer(ToolChoice::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): ToolChoice { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + ToolChoice(unionMember1 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + ToolChoice(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> ToolChoice(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(ToolChoice::class) { + + override fun serialize( + value: ToolChoice, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unionMember1 != null -> generator.writeObject(value.unionMember1) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid ToolChoice") + } + } + } + + class UnionMember1 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UnionMember1]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember1]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember1: UnionMember1) = apply { + additionalProperties = unionMember1.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember1]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UnionMember1 = UnionMember1(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember1 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember1 && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "UnionMember1{additionalProperties=$additionalProperties}" + } + } + + class Tool + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Tool]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Tool]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(tool: Tool) = apply { + additionalProperties = tool.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Tool]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Tool = Tool(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Tool = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Tool && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Tool{additionalProperties=$additionalProperties}" + } override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is ChatCompleteParams && model == other.model && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is ChatCompleteParams && + pathModel == other.pathModel && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(model, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(pathModel, body, additionalHeaders, additionalQueryParams) override fun toString() = - "ChatCompleteParams{model=$model, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" + "ChatCompleteParams{pathModel=$pathModel, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/chat/ChatCompleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/chat/ChatCompleteResponse.kt index 3751b704..416aa2b6 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/chat/ChatCompleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/engines/chat/ChatCompleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.engines.chat import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class ChatCompleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [EuAssemblyaiCreateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): EuAssemblyaiCreateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [EuAssemblyaiCreateParams]. */ @JvmStatic fun builder() = Builder() } @@ -60,7 +58,10 @@ private constructor( euAssemblyaiCreateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -186,30 +187,22 @@ private constructor( * Returns an immutable instance of [EuAssemblyaiCreateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): EuAssemblyaiCreateParams = EuAssemblyaiCreateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -222,10 +215,15 @@ private constructor( return true } - return /* spotless:off */ other is EuAssemblyaiCreateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is EuAssemblyaiCreateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "EuAssemblyaiCreateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiCreateResponse.kt index eee787ef..58a5472e 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.euassemblyai import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class EuAssemblyaiCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [EuAssemblyaiDeleteParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): EuAssemblyaiDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [EuAssemblyaiDeleteParams]. */ @JvmStatic fun builder() = Builder() } @@ -60,7 +58,10 @@ private constructor( euAssemblyaiDeleteParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -186,30 +187,22 @@ private constructor( * Returns an immutable instance of [EuAssemblyaiDeleteParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): EuAssemblyaiDeleteParams = EuAssemblyaiDeleteParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -222,10 +215,15 @@ private constructor( return true } - return /* spotless:off */ other is EuAssemblyaiDeleteParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is EuAssemblyaiDeleteParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "EuAssemblyaiDeleteParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiDeleteResponse.kt index dbe3b85b..ad8c6bc5 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.euassemblyai import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class EuAssemblyaiDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [EuAssemblyaiPatchParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): EuAssemblyaiPatchParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [EuAssemblyaiPatchParams]. */ @JvmStatic fun builder() = Builder() } @@ -60,7 +58,10 @@ private constructor( euAssemblyaiPatchParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -186,30 +187,22 @@ private constructor( * Returns an immutable instance of [EuAssemblyaiPatchParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): EuAssemblyaiPatchParams = EuAssemblyaiPatchParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -222,10 +215,15 @@ private constructor( return true } - return /* spotless:off */ other is EuAssemblyaiPatchParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is EuAssemblyaiPatchParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "EuAssemblyaiPatchParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiPatchResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiPatchResponse.kt index fbcd409f..9c185a6d 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiPatchResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiPatchResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.euassemblyai import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class EuAssemblyaiPatchResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(endpoint) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): EuAssemblyaiRetrieveParams = builder().build() + /** * Returns a mutable builder for constructing an instance of [EuAssemblyaiRetrieveParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` */ @JvmStatic fun builder() = Builder() } @@ -51,7 +51,10 @@ private constructor( additionalQueryParams = euAssemblyaiRetrieveParams.additionalQueryParams.toBuilder() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -155,17 +158,10 @@ private constructor( * Returns an immutable instance of [EuAssemblyaiRetrieveParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): EuAssemblyaiRetrieveParams = EuAssemblyaiRetrieveParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -173,7 +169,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -186,10 +182,13 @@ private constructor( return true } - return /* spotless:off */ other is EuAssemblyaiRetrieveParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is EuAssemblyaiRetrieveParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(endpoint, additionalHeaders, additionalQueryParams) override fun toString() = "EuAssemblyaiRetrieveParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiRetrieveResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiRetrieveResponse.kt index c928d696..9fb8720c 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiRetrieveResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiRetrieveResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.euassemblyai import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class EuAssemblyaiRetrieveResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [EuAssemblyaiUpdateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): EuAssemblyaiUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [EuAssemblyaiUpdateParams]. */ @JvmStatic fun builder() = Builder() } @@ -60,7 +58,10 @@ private constructor( euAssemblyaiUpdateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -186,30 +187,22 @@ private constructor( * Returns an immutable instance of [EuAssemblyaiUpdateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): EuAssemblyaiUpdateParams = EuAssemblyaiUpdateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -222,10 +215,15 @@ private constructor( return true } - return /* spotless:off */ other is EuAssemblyaiUpdateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is EuAssemblyaiUpdateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "EuAssemblyaiUpdateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiUpdateResponse.kt index 998834f3..9b0d2b12 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/euassemblyai/EuAssemblyaiUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.euassemblyai import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class EuAssemblyaiUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(provider) /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly @@ -59,6 +64,24 @@ private constructor( */ fun customLlmProvider(): Optional = body.customLlmProvider() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmMetadata(): Optional = body.litellmMetadata() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun targetModelNames(): Optional = body.targetModelNames() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun targetStorage(): Optional = body.targetStorage() + /** * Returns the raw multipart value of [file]. * @@ -81,8 +104,36 @@ private constructor( */ fun _customLlmProvider(): MultipartField = body._customLlmProvider() + /** + * Returns the raw multipart value of [litellmMetadata]. + * + * Unlike [litellmMetadata], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _litellmMetadata(): MultipartField = body._litellmMetadata() + + /** + * Returns the raw multipart value of [targetModelNames]. + * + * Unlike [targetModelNames], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _targetModelNames(): MultipartField = body._targetModelNames() + + /** + * Returns the raw multipart value of [targetStorage]. + * + * Unlike [targetStorage], this method doesn't throw if the multipart field has an unexpected + * type. + */ + fun _targetStorage(): MultipartField = body._targetStorage() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -94,7 +145,6 @@ private constructor( * * The following fields are required: * ```java - * .provider() * .file() * .purpose() * ``` @@ -118,7 +168,24 @@ private constructor( additionalQueryParams = fileCreateParams.additionalQueryParams.toBuilder() } - fun provider(provider: String) = apply { this.provider = provider } + fun provider(provider: String?) = apply { this.provider = provider } + + /** Alias for calling [Builder.provider] with `provider.orElse(null)`. */ + fun provider(provider: Optional) = provider(provider.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [file] + * - [purpose] + * - [customLlmProvider] + * - [litellmMetadata] + * - [targetModelNames] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } fun file(file: InputStream) = apply { body.file(file) } @@ -133,7 +200,7 @@ private constructor( fun file(file: ByteArray) = apply { body.file(file) } - fun file(file: Path) = apply { body.file(file) } + fun file(path: Path) = apply { body.file(path) } fun purpose(purpose: String) = apply { body.purpose(purpose) } @@ -160,6 +227,72 @@ private constructor( body.customLlmProvider(customLlmProvider) } + fun litellmMetadata(litellmMetadata: String?) = apply { + body.litellmMetadata(litellmMetadata) + } + + /** Alias for calling [Builder.litellmMetadata] with `litellmMetadata.orElse(null)`. */ + fun litellmMetadata(litellmMetadata: Optional) = + litellmMetadata(litellmMetadata.getOrNull()) + + /** + * Sets [Builder.litellmMetadata] to an arbitrary multipart value. + * + * You should usually call [Builder.litellmMetadata] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun litellmMetadata(litellmMetadata: MultipartField) = apply { + body.litellmMetadata(litellmMetadata) + } + + fun targetModelNames(targetModelNames: String) = apply { + body.targetModelNames(targetModelNames) + } + + /** + * Sets [Builder.targetModelNames] to an arbitrary multipart value. + * + * You should usually call [Builder.targetModelNames] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun targetModelNames(targetModelNames: MultipartField) = apply { + body.targetModelNames(targetModelNames) + } + + fun targetStorage(targetStorage: String) = apply { body.targetStorage(targetStorage) } + + /** + * Sets [Builder.targetStorage] to an arbitrary multipart value. + * + * You should usually call [Builder.targetStorage] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun targetStorage(targetStorage: MultipartField) = apply { + body.targetStorage(targetStorage) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() putAllAdditionalHeaders(additionalHeaders) @@ -265,7 +398,6 @@ private constructor( * * The following fields are required: * ```java - * .provider() * .file() * .purpose() * ``` @@ -274,25 +406,27 @@ private constructor( */ fun build(): FileCreateParams = FileCreateParams( - checkRequired("provider", provider), + provider, body.build(), additionalHeaders.build(), additionalQueryParams.build(), ) } - @JvmSynthetic - internal fun _body(): Map> = - mapOf( + fun _body(): Map> = + (mapOf( "file" to _file(), "purpose" to _purpose(), "custom_llm_provider" to _customLlmProvider(), - ) + "litellm_metadata" to _litellmMetadata(), + "target_model_names" to _targetModelNames(), + "target_storage" to _targetStorage(), + ) + _additionalBodyProperties().mapValues { (_, value) -> MultipartField.of(value) }) .toImmutable() fun _pathParam(index: Int): String = when (index) { - 0 -> provider + 0 -> provider ?: "" else -> "" } @@ -305,6 +439,10 @@ private constructor( private val file: MultipartField, private val purpose: MultipartField, private val customLlmProvider: MultipartField, + private val litellmMetadata: MultipartField, + private val targetModelNames: MultipartField, + private val targetStorage: MultipartField, + private val additionalProperties: MutableMap, ) { /** @@ -324,7 +462,27 @@ private constructor( * server responded with an unexpected value). */ fun customLlmProvider(): Optional = - Optional.ofNullable(customLlmProvider.value.getNullable("custom_llm_provider")) + customLlmProvider.value.getOptional("custom_llm_provider") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmMetadata(): Optional = + litellmMetadata.value.getOptional("litellm_metadata") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun targetModelNames(): Optional = + targetModelNames.value.getOptional("target_model_names") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun targetStorage(): Optional = targetStorage.value.getOptional("target_storage") /** * Returns the raw multipart value of [file]. @@ -351,6 +509,46 @@ private constructor( @ExcludeMissing fun _customLlmProvider(): MultipartField = customLlmProvider + /** + * Returns the raw multipart value of [litellmMetadata]. + * + * Unlike [litellmMetadata], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("litellm_metadata") + @ExcludeMissing + fun _litellmMetadata(): MultipartField = litellmMetadata + + /** + * Returns the raw multipart value of [targetModelNames]. + * + * Unlike [targetModelNames], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("target_model_names") + @ExcludeMissing + fun _targetModelNames(): MultipartField = targetModelNames + + /** + * Returns the raw multipart value of [targetStorage]. + * + * Unlike [targetStorage], this method doesn't throw if the multipart field has an + * unexpected type. + */ + @JsonProperty("target_storage") + @ExcludeMissing + fun _targetStorage(): MultipartField = targetStorage + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + fun toBuilder() = Builder().from(this) companion object { @@ -373,12 +571,20 @@ private constructor( private var file: MultipartField? = null private var purpose: MultipartField? = null private var customLlmProvider: MultipartField = MultipartField.of(null) + private var litellmMetadata: MultipartField = MultipartField.of(null) + private var targetModelNames: MultipartField = MultipartField.of(null) + private var targetStorage: MultipartField = MultipartField.of(null) + private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(body: Body) = apply { file = body.file purpose = body.purpose customLlmProvider = body.customLlmProvider + litellmMetadata = body.litellmMetadata + targetModelNames = body.targetModelNames + targetStorage = body.targetStorage + additionalProperties = body.additionalProperties.toMutableMap() } fun file(file: InputStream) = file(MultipartField.of(file)) @@ -394,11 +600,11 @@ private constructor( fun file(file: ByteArray) = file(file.inputStream()) - fun file(file: Path) = + fun file(path: Path) = file( MultipartField.builder() - .value(file.inputStream()) - .filename(file.name) + .value(path.inputStream()) + .filename(path.name) .build() ) @@ -427,6 +633,71 @@ private constructor( this.customLlmProvider = customLlmProvider } + fun litellmMetadata(litellmMetadata: String?) = + litellmMetadata(MultipartField.of(litellmMetadata)) + + /** Alias for calling [Builder.litellmMetadata] with `litellmMetadata.orElse(null)`. */ + fun litellmMetadata(litellmMetadata: Optional) = + litellmMetadata(litellmMetadata.getOrNull()) + + /** + * Sets [Builder.litellmMetadata] to an arbitrary multipart value. + * + * You should usually call [Builder.litellmMetadata] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun litellmMetadata(litellmMetadata: MultipartField) = apply { + this.litellmMetadata = litellmMetadata + } + + fun targetModelNames(targetModelNames: String) = + targetModelNames(MultipartField.of(targetModelNames)) + + /** + * Sets [Builder.targetModelNames] to an arbitrary multipart value. + * + * You should usually call [Builder.targetModelNames] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun targetModelNames(targetModelNames: MultipartField) = apply { + this.targetModelNames = targetModelNames + } + + fun targetStorage(targetStorage: String) = + targetStorage(MultipartField.of(targetStorage)) + + /** + * Sets [Builder.targetStorage] to an arbitrary multipart value. + * + * You should usually call [Builder.targetStorage] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun targetStorage(targetStorage: MultipartField) = apply { + this.targetStorage = targetStorage + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + /** * Returns an immutable instance of [Body]. * @@ -445,6 +716,10 @@ private constructor( checkRequired("file", file), checkRequired("purpose", purpose), customLlmProvider, + litellmMetadata, + targetModelNames, + targetStorage, + additionalProperties.toMutableMap(), ) } @@ -458,25 +733,51 @@ private constructor( file() purpose() customLlmProvider() + litellmMetadata() + targetModelNames() + targetStorage() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && file == other.file && purpose == other.purpose && customLlmProvider == other.customLlmProvider /* spotless:on */ + return other is Body && + file == other.file && + purpose == other.purpose && + customLlmProvider == other.customLlmProvider && + litellmMetadata == other.litellmMetadata && + targetModelNames == other.targetModelNames && + targetStorage == other.targetStorage && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(file, purpose, customLlmProvider) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + file, + purpose, + customLlmProvider, + litellmMetadata, + targetModelNames, + targetStorage, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "Body{file=$file, purpose=$purpose, customLlmProvider=$customLlmProvider}" + "Body{file=$file, purpose=$purpose, customLlmProvider=$customLlmProvider, litellmMetadata=$litellmMetadata, targetModelNames=$targetModelNames, targetStorage=$targetStorage, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { @@ -484,10 +785,15 @@ private constructor( return true } - return /* spotless:off */ other is FileCreateParams && provider == other.provider && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is FileCreateParams && + provider == other.provider && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(provider, body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(provider, body, additionalHeaders, additionalQueryParams) override fun toString() = "FileCreateParams{provider=$provider, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileCreateResponse.kt index 88af7d49..3c498779 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.files import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class FileCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, @@ -35,12 +36,15 @@ private constructor( fun provider(): String = provider - fun fileId(): String = fileId + fun fileId(): Optional = Optional.ofNullable(fileId) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -53,7 +57,6 @@ private constructor( * The following fields are required: * ```java * .provider() - * .fileId() * ``` */ @JvmStatic fun builder() = Builder() @@ -79,7 +82,10 @@ private constructor( fun provider(provider: String) = apply { this.provider = provider } - fun fileId(fileId: String) = apply { this.fileId = fileId } + fun fileId(fileId: String?) = apply { this.fileId = fileId } + + /** Alias for calling [Builder.fileId] with `fileId.orElse(null)`. */ + fun fileId(fileId: Optional) = fileId(fileId.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -209,7 +215,6 @@ private constructor( * The following fields are required: * ```java * .provider() - * .fileId() * ``` * * @throws IllegalStateException if any required field is unset. @@ -217,21 +222,20 @@ private constructor( fun build(): FileDeleteParams = FileDeleteParams( checkRequired("provider", provider), - checkRequired("fileId", fileId), + fileId, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { 0 -> provider - 1 -> fileId + 1 -> fileId ?: "" else -> "" } @@ -244,10 +248,22 @@ private constructor( return true } - return /* spotless:off */ other is FileDeleteParams && provider == other.provider && fileId == other.fileId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is FileDeleteParams && + provider == other.provider && + fileId == other.fileId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(provider, fileId, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + provider, + fileId, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) override fun toString() = "FileDeleteParams{provider=$provider, fileId=$fileId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileDeleteResponse.kt index 6e1d4e4d..ab61eaa0 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.files import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class FileDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(provider) fun purpose(): Optional = Optional.ofNullable(purpose) + fun targetModelNames(): Optional = Optional.ofNullable(targetModelNames) + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [FileListParams]. - * - * The following fields are required: - * ```java - * .provider() - * ``` - */ + @JvmStatic fun none(): FileListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [FileListParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,6 +58,7 @@ private constructor( private var provider: String? = null private var purpose: String? = null + private var targetModelNames: String? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @@ -66,17 +66,29 @@ private constructor( internal fun from(fileListParams: FileListParams) = apply { provider = fileListParams.provider purpose = fileListParams.purpose + targetModelNames = fileListParams.targetModelNames additionalHeaders = fileListParams.additionalHeaders.toBuilder() additionalQueryParams = fileListParams.additionalQueryParams.toBuilder() } - fun provider(provider: String) = apply { this.provider = provider } + fun provider(provider: String?) = apply { this.provider = provider } + + /** Alias for calling [Builder.provider] with `provider.orElse(null)`. */ + fun provider(provider: Optional) = provider(provider.getOrNull()) fun purpose(purpose: String?) = apply { this.purpose = purpose } /** Alias for calling [Builder.purpose] with `purpose.orElse(null)`. */ fun purpose(purpose: Optional) = purpose(purpose.getOrNull()) + fun targetModelNames(targetModelNames: String?) = apply { + this.targetModelNames = targetModelNames + } + + /** Alias for calling [Builder.targetModelNames] with `targetModelNames.orElse(null)`. */ + fun targetModelNames(targetModelNames: Optional) = + targetModelNames(targetModelNames.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() putAllAdditionalHeaders(additionalHeaders) @@ -179,18 +191,12 @@ private constructor( * Returns an immutable instance of [FileListParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .provider() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): FileListParams = FileListParams( - checkRequired("provider", provider), + provider, purpose, + targetModelNames, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -198,7 +204,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { - 0 -> provider + 0 -> provider ?: "" else -> "" } @@ -208,6 +214,7 @@ private constructor( QueryParams.builder() .apply { purpose?.let { put("purpose", it) } + targetModelNames?.let { put("target_model_names", it) } putAll(additionalQueryParams) } .build() @@ -217,11 +224,17 @@ private constructor( return true } - return /* spotless:off */ other is FileListParams && provider == other.provider && purpose == other.purpose && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is FileListParams && + provider == other.provider && + purpose == other.purpose && + targetModelNames == other.targetModelNames && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(provider, purpose, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(provider, purpose, targetModelNames, additionalHeaders, additionalQueryParams) override fun toString() = - "FileListParams{provider=$provider, purpose=$purpose, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "FileListParams{provider=$provider, purpose=$purpose, targetModelNames=$targetModelNames, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileListResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileListResponse.kt index 4c178531..085865ad 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileListResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileListResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.files import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class FileListResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(fileId) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -47,7 +51,6 @@ private constructor( * The following fields are required: * ```java * .provider() - * .fileId() * ``` */ @JvmStatic fun builder() = Builder() @@ -71,7 +74,10 @@ private constructor( fun provider(provider: String) = apply { this.provider = provider } - fun fileId(fileId: String) = apply { this.fileId = fileId } + fun fileId(fileId: String?) = apply { this.fileId = fileId } + + /** Alias for calling [Builder.fileId] with `fileId.orElse(null)`. */ + fun fileId(fileId: Optional) = fileId(fileId.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -179,7 +185,6 @@ private constructor( * The following fields are required: * ```java * .provider() - * .fileId() * ``` * * @throws IllegalStateException if any required field is unset. @@ -187,7 +192,7 @@ private constructor( fun build(): FileRetrieveParams = FileRetrieveParams( checkRequired("provider", provider), - checkRequired("fileId", fileId), + fileId, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -196,7 +201,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { 0 -> provider - 1 -> fileId + 1 -> fileId ?: "" else -> "" } @@ -209,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is FileRetrieveParams && provider == other.provider && fileId == other.fileId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is FileRetrieveParams && + provider == other.provider && + fileId == other.fileId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(provider, fileId, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(provider, fileId, additionalHeaders, additionalQueryParams) override fun toString() = "FileRetrieveParams{provider=$provider, fileId=$fileId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileRetrieveResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileRetrieveResponse.kt index 4dde1fbe..6f96ec9f 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileRetrieveResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/FileRetrieveResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.files import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class FileRetrieveResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(fileId) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -48,7 +52,6 @@ private constructor( * The following fields are required: * ```java * .provider() - * .fileId() * ``` */ @JvmStatic fun builder() = Builder() @@ -72,7 +75,10 @@ private constructor( fun provider(provider: String) = apply { this.provider = provider } - fun fileId(fileId: String) = apply { this.fileId = fileId } + fun fileId(fileId: String?) = apply { this.fileId = fileId } + + /** Alias for calling [Builder.fileId] with `fileId.orElse(null)`. */ + fun fileId(fileId: Optional) = fileId(fileId.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -180,7 +186,6 @@ private constructor( * The following fields are required: * ```java * .provider() - * .fileId() * ``` * * @throws IllegalStateException if any required field is unset. @@ -188,7 +193,7 @@ private constructor( fun build(): ContentRetrieveParams = ContentRetrieveParams( checkRequired("provider", provider), - checkRequired("fileId", fileId), + fileId, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -197,7 +202,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { 0 -> provider - 1 -> fileId + 1 -> fileId ?: "" else -> "" } @@ -210,10 +215,15 @@ private constructor( return true } - return /* spotless:off */ other is ContentRetrieveParams && provider == other.provider && fileId == other.fileId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is ContentRetrieveParams && + provider == other.provider && + fileId == other.fileId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(provider, fileId, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(provider, fileId, additionalHeaders, additionalQueryParams) override fun toString() = "ContentRetrieveParams{provider=$provider, fileId=$fileId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/content/ContentRetrieveResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/content/ContentRetrieveResponse.kt index 9ca8be1d..ad1c935f 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/content/ContentRetrieveResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/files/content/ContentRetrieveResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.files.content import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class ContentRetrieveResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap = body.hyperparameters() - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun integrations(): Optional> = body.integrations() - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun seed(): Optional = body.seed() - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun suffix(): Optional = body.suffix() - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun validationFile(): Optional = body.validationFile() - - /** - * Returns the raw JSON value of [customLlmProvider]. - * - * Unlike [customLlmProvider], this method doesn't throw if the JSON field has an unexpected - * type. - */ - fun _customLlmProvider(): JsonField = body._customLlmProvider() - - /** - * Returns the raw JSON value of [model]. - * - * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. - */ - fun _model(): JsonField = body._model() - - /** - * Returns the raw JSON value of [trainingFile]. - * - * Unlike [trainingFile], this method doesn't throw if the JSON field has an unexpected type. - */ - fun _trainingFile(): JsonField = body._trainingFile() - - /** - * Returns the raw JSON value of [hyperparameters]. - * - * Unlike [hyperparameters], this method doesn't throw if the JSON field has an unexpected type. - */ - fun _hyperparameters(): JsonField = body._hyperparameters() - - /** - * Returns the raw JSON value of [integrations]. - * - * Unlike [integrations], this method doesn't throw if the JSON field has an unexpected type. - */ - fun _integrations(): JsonField> = body._integrations() - - /** - * Returns the raw JSON value of [seed]. - * - * Unlike [seed], this method doesn't throw if the JSON field has an unexpected type. - */ - fun _seed(): JsonField = body._seed() - - /** - * Returns the raw JSON value of [suffix]. - * - * Unlike [suffix], this method doesn't throw if the JSON field has an unexpected type. - */ - fun _suffix(): JsonField = body._suffix() - - /** - * Returns the raw JSON value of [validationFile]. - * - * Unlike [validationFile], this method doesn't throw if the JSON field has an unexpected type. - */ - fun _validationFile(): JsonField = body._validationFile() - - fun _additionalBodyProperties(): Map = body._additionalProperties() + fun _additionalBodyProperties(): Map = + liteLlmFineTuningJobCreate._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -177,9 +53,7 @@ private constructor( * * The following fields are required: * ```java - * .customLlmProvider() - * .model() - * .trainingFile() + * .liteLlmFineTuningJobCreate() * ``` */ @JvmStatic fun builder() = Builder() @@ -188,167 +62,22 @@ private constructor( /** A builder for [JobCreateParams]. */ class Builder internal constructor() { - private var body: Body.Builder = Body.builder() + private var liteLlmFineTuningJobCreate: LiteLlmFineTuningJobCreate? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(jobCreateParams: JobCreateParams) = apply { - body = jobCreateParams.body.toBuilder() + liteLlmFineTuningJobCreate = jobCreateParams.liteLlmFineTuningJobCreate additionalHeaders = jobCreateParams.additionalHeaders.toBuilder() additionalQueryParams = jobCreateParams.additionalQueryParams.toBuilder() } - fun customLlmProvider(customLlmProvider: CustomLlmProvider) = apply { - body.customLlmProvider(customLlmProvider) - } - - /** - * Sets [Builder.customLlmProvider] to an arbitrary JSON value. - * - * You should usually call [Builder.customLlmProvider] with a well-typed [CustomLlmProvider] - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun customLlmProvider(customLlmProvider: JsonField) = apply { - body.customLlmProvider(customLlmProvider) - } - - fun model(model: String) = apply { body.model(model) } - - /** - * Sets [Builder.model] to an arbitrary JSON value. - * - * You should usually call [Builder.model] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun model(model: JsonField) = apply { body.model(model) } - - fun trainingFile(trainingFile: String) = apply { body.trainingFile(trainingFile) } - - /** - * Sets [Builder.trainingFile] to an arbitrary JSON value. - * - * You should usually call [Builder.trainingFile] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun trainingFile(trainingFile: JsonField) = apply { - body.trainingFile(trainingFile) - } - - fun hyperparameters(hyperparameters: Hyperparameters?) = apply { - body.hyperparameters(hyperparameters) - } - - /** Alias for calling [Builder.hyperparameters] with `hyperparameters.orElse(null)`. */ - fun hyperparameters(hyperparameters: Optional) = - hyperparameters(hyperparameters.getOrNull()) - - /** - * Sets [Builder.hyperparameters] to an arbitrary JSON value. - * - * You should usually call [Builder.hyperparameters] with a well-typed [Hyperparameters] - * value instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun hyperparameters(hyperparameters: JsonField) = apply { - body.hyperparameters(hyperparameters) - } - - fun integrations(integrations: List?) = apply { body.integrations(integrations) } - - /** Alias for calling [Builder.integrations] with `integrations.orElse(null)`. */ - fun integrations(integrations: Optional>) = - integrations(integrations.getOrNull()) - - /** - * Sets [Builder.integrations] to an arbitrary JSON value. - * - * You should usually call [Builder.integrations] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun integrations(integrations: JsonField>) = apply { - body.integrations(integrations) - } - - /** - * Adds a single [String] to [integrations]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addIntegration(integration: String) = apply { body.addIntegration(integration) } - - fun seed(seed: Long?) = apply { body.seed(seed) } - - /** - * Alias for [Builder.seed]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun seed(seed: Long) = seed(seed as Long?) - - /** Alias for calling [Builder.seed] with `seed.orElse(null)`. */ - fun seed(seed: Optional) = seed(seed.getOrNull()) - - /** - * Sets [Builder.seed] to an arbitrary JSON value. - * - * You should usually call [Builder.seed] with a well-typed [Long] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun seed(seed: JsonField) = apply { body.seed(seed) } - - fun suffix(suffix: String?) = apply { body.suffix(suffix) } - - /** Alias for calling [Builder.suffix] with `suffix.orElse(null)`. */ - fun suffix(suffix: Optional) = suffix(suffix.getOrNull()) - - /** - * Sets [Builder.suffix] to an arbitrary JSON value. - * - * You should usually call [Builder.suffix] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun suffix(suffix: JsonField) = apply { body.suffix(suffix) } - - fun validationFile(validationFile: String?) = apply { body.validationFile(validationFile) } - - /** Alias for calling [Builder.validationFile] with `validationFile.orElse(null)`. */ - fun validationFile(validationFile: Optional) = - validationFile(validationFile.getOrNull()) - - /** - * Sets [Builder.validationFile] to an arbitrary JSON value. - * - * You should usually call [Builder.validationFile] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun validationFile(validationFile: JsonField) = apply { - body.validationFile(validationFile) - } - - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } - - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } - - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + fun liteLlmFineTuningJobCreate(liteLlmFineTuningJobCreate: LiteLlmFineTuningJobCreate) = apply { - body.putAllAdditionalProperties(additionalBodyProperties) + this.liteLlmFineTuningJobCreate = liteLlmFineTuningJobCreate } - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } - fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() putAllAdditionalHeaders(additionalHeaders) @@ -454,1217 +183,39 @@ private constructor( * * The following fields are required: * ```java - * .customLlmProvider() - * .model() - * .trainingFile() + * .liteLlmFineTuningJobCreate() * ``` * * @throws IllegalStateException if any required field is unset. */ fun build(): JobCreateParams = - JobCreateParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + JobCreateParams( + checkRequired("liteLlmFineTuningJobCreate", liteLlmFineTuningJobCreate), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - @JvmSynthetic internal fun _body(): Body = body + fun _body(): LiteLlmFineTuningJobCreate = liteLlmFineTuningJobCreate override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams - class Body - private constructor( - private val customLlmProvider: JsonField, - private val model: JsonField, - private val trainingFile: JsonField, - private val hyperparameters: JsonField, - private val integrations: JsonField>, - private val seed: JsonField, - private val suffix: JsonField, - private val validationFile: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("custom_llm_provider") - @ExcludeMissing - customLlmProvider: JsonField = JsonMissing.of(), - @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of(), - @JsonProperty("training_file") - @ExcludeMissing - trainingFile: JsonField = JsonMissing.of(), - @JsonProperty("hyperparameters") - @ExcludeMissing - hyperparameters: JsonField = JsonMissing.of(), - @JsonProperty("integrations") - @ExcludeMissing - integrations: JsonField> = JsonMissing.of(), - @JsonProperty("seed") @ExcludeMissing seed: JsonField = JsonMissing.of(), - @JsonProperty("suffix") @ExcludeMissing suffix: JsonField = JsonMissing.of(), - @JsonProperty("validation_file") - @ExcludeMissing - validationFile: JsonField = JsonMissing.of(), - ) : this( - customLlmProvider, - model, - trainingFile, - hyperparameters, - integrations, - seed, - suffix, - validationFile, - mutableMapOf(), - ) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun customLlmProvider(): CustomLlmProvider = - customLlmProvider.getRequired("custom_llm_provider") - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun model(): String = model.getRequired("model") - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). - */ - fun trainingFile(): String = trainingFile.getRequired("training_file") - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun hyperparameters(): Optional = - Optional.ofNullable(hyperparameters.getNullable("hyperparameters")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun integrations(): Optional> = - Optional.ofNullable(integrations.getNullable("integrations")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun seed(): Optional = Optional.ofNullable(seed.getNullable("seed")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun suffix(): Optional = Optional.ofNullable(suffix.getNullable("suffix")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun validationFile(): Optional = - Optional.ofNullable(validationFile.getNullable("validation_file")) - - /** - * Returns the raw JSON value of [customLlmProvider]. - * - * Unlike [customLlmProvider], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("custom_llm_provider") - @ExcludeMissing - fun _customLlmProvider(): JsonField = customLlmProvider - - /** - * Returns the raw JSON value of [model]. - * - * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model - - /** - * Returns the raw JSON value of [trainingFile]. - * - * Unlike [trainingFile], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("training_file") - @ExcludeMissing - fun _trainingFile(): JsonField = trainingFile - - /** - * Returns the raw JSON value of [hyperparameters]. - * - * Unlike [hyperparameters], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("hyperparameters") - @ExcludeMissing - fun _hyperparameters(): JsonField = hyperparameters - - /** - * Returns the raw JSON value of [integrations]. - * - * Unlike [integrations], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("integrations") - @ExcludeMissing - fun _integrations(): JsonField> = integrations - - /** - * Returns the raw JSON value of [seed]. - * - * Unlike [seed], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("seed") @ExcludeMissing fun _seed(): JsonField = seed - - /** - * Returns the raw JSON value of [suffix]. - * - * Unlike [suffix], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("suffix") @ExcludeMissing fun _suffix(): JsonField = suffix - - /** - * Returns the raw JSON value of [validationFile]. - * - * Unlike [validationFile], this method doesn't throw if the JSON field has an unexpected - * type. - */ - @JsonProperty("validation_file") - @ExcludeMissing - fun _validationFile(): JsonField = validationFile - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of [Body]. - * - * The following fields are required: - * ```java - * .customLlmProvider() - * .model() - * .trainingFile() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var customLlmProvider: JsonField? = null - private var model: JsonField? = null - private var trainingFile: JsonField? = null - private var hyperparameters: JsonField = JsonMissing.of() - private var integrations: JsonField>? = null - private var seed: JsonField = JsonMissing.of() - private var suffix: JsonField = JsonMissing.of() - private var validationFile: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - customLlmProvider = body.customLlmProvider - model = body.model - trainingFile = body.trainingFile - hyperparameters = body.hyperparameters - integrations = body.integrations.map { it.toMutableList() } - seed = body.seed - suffix = body.suffix - validationFile = body.validationFile - additionalProperties = body.additionalProperties.toMutableMap() - } - - fun customLlmProvider(customLlmProvider: CustomLlmProvider) = - customLlmProvider(JsonField.of(customLlmProvider)) - - /** - * Sets [Builder.customLlmProvider] to an arbitrary JSON value. - * - * You should usually call [Builder.customLlmProvider] with a well-typed - * [CustomLlmProvider] value instead. This method is primarily for setting the field to - * an undocumented or not yet supported value. - */ - fun customLlmProvider(customLlmProvider: JsonField) = apply { - this.customLlmProvider = customLlmProvider - } - - fun model(model: String) = model(JsonField.of(model)) - - /** - * Sets [Builder.model] to an arbitrary JSON value. - * - * You should usually call [Builder.model] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun model(model: JsonField) = apply { this.model = model } - - fun trainingFile(trainingFile: String) = trainingFile(JsonField.of(trainingFile)) - - /** - * Sets [Builder.trainingFile] to an arbitrary JSON value. - * - * You should usually call [Builder.trainingFile] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun trainingFile(trainingFile: JsonField) = apply { - this.trainingFile = trainingFile - } - - fun hyperparameters(hyperparameters: Hyperparameters?) = - hyperparameters(JsonField.ofNullable(hyperparameters)) - - /** Alias for calling [Builder.hyperparameters] with `hyperparameters.orElse(null)`. */ - fun hyperparameters(hyperparameters: Optional) = - hyperparameters(hyperparameters.getOrNull()) - - /** - * Sets [Builder.hyperparameters] to an arbitrary JSON value. - * - * You should usually call [Builder.hyperparameters] with a well-typed [Hyperparameters] - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun hyperparameters(hyperparameters: JsonField) = apply { - this.hyperparameters = hyperparameters - } - - fun integrations(integrations: List?) = - integrations(JsonField.ofNullable(integrations)) - - /** Alias for calling [Builder.integrations] with `integrations.orElse(null)`. */ - fun integrations(integrations: Optional>) = - integrations(integrations.getOrNull()) - - /** - * Sets [Builder.integrations] to an arbitrary JSON value. - * - * You should usually call [Builder.integrations] with a well-typed `List` value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun integrations(integrations: JsonField>) = apply { - this.integrations = integrations.map { it.toMutableList() } - } - - /** - * Adds a single [String] to [integrations]. - * - * @throws IllegalStateException if the field was previously set to a non-list. - */ - fun addIntegration(integration: String) = apply { - integrations = - (integrations ?: JsonField.of(mutableListOf())).also { - checkKnown("integrations", it).add(integration) - } - } - - fun seed(seed: Long?) = seed(JsonField.ofNullable(seed)) - - /** - * Alias for [Builder.seed]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun seed(seed: Long) = seed(seed as Long?) - - /** Alias for calling [Builder.seed] with `seed.orElse(null)`. */ - fun seed(seed: Optional) = seed(seed.getOrNull()) - - /** - * Sets [Builder.seed] to an arbitrary JSON value. - * - * You should usually call [Builder.seed] with a well-typed [Long] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun seed(seed: JsonField) = apply { this.seed = seed } - - fun suffix(suffix: String?) = suffix(JsonField.ofNullable(suffix)) - - /** Alias for calling [Builder.suffix] with `suffix.orElse(null)`. */ - fun suffix(suffix: Optional) = suffix(suffix.getOrNull()) - - /** - * Sets [Builder.suffix] to an arbitrary JSON value. - * - * You should usually call [Builder.suffix] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun suffix(suffix: JsonField) = apply { this.suffix = suffix } - - fun validationFile(validationFile: String?) = - validationFile(JsonField.ofNullable(validationFile)) - - /** Alias for calling [Builder.validationFile] with `validationFile.orElse(null)`. */ - fun validationFile(validationFile: Optional) = - validationFile(validationFile.getOrNull()) - - /** - * Sets [Builder.validationFile] to an arbitrary JSON value. - * - * You should usually call [Builder.validationFile] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun validationFile(validationFile: JsonField) = apply { - this.validationFile = validationFile - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Body]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .customLlmProvider() - * .model() - * .trainingFile() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): Body = - Body( - checkRequired("customLlmProvider", customLlmProvider), - checkRequired("model", model), - checkRequired("trainingFile", trainingFile), - hyperparameters, - (integrations ?: JsonMissing.of()).map { it.toImmutable() }, - seed, - suffix, - validationFile, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - customLlmProvider() - model() - trainingFile() - hyperparameters().ifPresent { it.validate() } - integrations() - seed() - suffix() - validationFile() - validated = true - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && customLlmProvider == other.customLlmProvider && model == other.model && trainingFile == other.trainingFile && hyperparameters == other.hyperparameters && integrations == other.integrations && seed == other.seed && suffix == other.suffix && validationFile == other.validationFile && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(customLlmProvider, model, trainingFile, hyperparameters, integrations, seed, suffix, validationFile, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{customLlmProvider=$customLlmProvider, model=$model, trainingFile=$trainingFile, hyperparameters=$hyperparameters, integrations=$integrations, seed=$seed, suffix=$suffix, validationFile=$validationFile, additionalProperties=$additionalProperties}" - } - - class CustomLlmProvider @JsonCreator private constructor(private val value: JsonField) : - Enum { - - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that doesn't - * match any known member, and you want to know that value. For example, if the SDK is on an - * older version than the API, then the API may respond with new members that the SDK is - * unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val OPENAI = of("openai") - - @JvmField val AZURE = of("azure") - - @JvmField val VERTEX_AI = of("vertex_ai") - - @JvmStatic fun of(value: String) = CustomLlmProvider(JsonField.of(value)) - } - - /** An enum containing [CustomLlmProvider]'s known values. */ - enum class Known { - OPENAI, - AZURE, - VERTEX_AI, - } - - /** - * An enum containing [CustomLlmProvider]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [CustomLlmProvider] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, if the - * SDK is on an older version than the API, then the API may respond with new members that - * the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - OPENAI, - AZURE, - VERTEX_AI, - /** - * An enum member indicating that [CustomLlmProvider] was instantiated with an unknown - * value. - */ - _UNKNOWN, - } - - /** - * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] - * if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if you want - * to throw for the unknown case. - */ - fun value(): Value = - when (this) { - OPENAI -> Value.OPENAI - AZURE -> Value.AZURE - VERTEX_AI -> Value.VERTEX_AI - else -> Value._UNKNOWN - } - - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and don't - * want to throw for the unknown case. - * - * @throws HanzoInvalidDataException if this class instance's value is a not a known member. - */ - fun known(): Known = - when (this) { - OPENAI -> Known.OPENAI - AZURE -> Known.AZURE - VERTEX_AI -> Known.VERTEX_AI - else -> throw HanzoInvalidDataException("Unknown CustomLlmProvider: $value") - } - - /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for debugging - * and generally doesn't throw. - * - * @throws HanzoInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is CustomLlmProvider && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - class Hyperparameters - private constructor( - private val batchSize: JsonField, - private val learningRateMultiplier: JsonField, - private val nEpochs: JsonField, - private val additionalProperties: MutableMap, - ) { - - @JsonCreator - private constructor( - @JsonProperty("batch_size") - @ExcludeMissing - batchSize: JsonField = JsonMissing.of(), - @JsonProperty("learning_rate_multiplier") - @ExcludeMissing - learningRateMultiplier: JsonField = JsonMissing.of(), - @JsonProperty("n_epochs") @ExcludeMissing nEpochs: JsonField = JsonMissing.of(), - ) : this(batchSize, learningRateMultiplier, nEpochs, mutableMapOf()) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun batchSize(): Optional = - Optional.ofNullable(batchSize.getNullable("batch_size")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun learningRateMultiplier(): Optional = - Optional.ofNullable(learningRateMultiplier.getNullable("learning_rate_multiplier")) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the - * server responded with an unexpected value). - */ - fun nEpochs(): Optional = Optional.ofNullable(nEpochs.getNullable("n_epochs")) - - /** - * Returns the raw JSON value of [batchSize]. - * - * Unlike [batchSize], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("batch_size") - @ExcludeMissing - fun _batchSize(): JsonField = batchSize - - /** - * Returns the raw JSON value of [learningRateMultiplier]. - * - * Unlike [learningRateMultiplier], this method doesn't throw if the JSON field has an - * unexpected type. - */ - @JsonProperty("learning_rate_multiplier") - @ExcludeMissing - fun _learningRateMultiplier(): JsonField = learningRateMultiplier - - /** - * Returns the raw JSON value of [nEpochs]. - * - * Unlike [nEpochs], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("n_epochs") @ExcludeMissing fun _nEpochs(): JsonField = nEpochs - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** Returns a mutable builder for constructing an instance of [Hyperparameters]. */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Hyperparameters]. */ - class Builder internal constructor() { - - private var batchSize: JsonField = JsonMissing.of() - private var learningRateMultiplier: JsonField = JsonMissing.of() - private var nEpochs: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(hyperparameters: Hyperparameters) = apply { - batchSize = hyperparameters.batchSize - learningRateMultiplier = hyperparameters.learningRateMultiplier - nEpochs = hyperparameters.nEpochs - additionalProperties = hyperparameters.additionalProperties.toMutableMap() - } - - fun batchSize(batchSize: BatchSize?) = batchSize(JsonField.ofNullable(batchSize)) - - /** Alias for calling [Builder.batchSize] with `batchSize.orElse(null)`. */ - fun batchSize(batchSize: Optional) = batchSize(batchSize.getOrNull()) - - /** - * Sets [Builder.batchSize] to an arbitrary JSON value. - * - * You should usually call [Builder.batchSize] with a well-typed [BatchSize] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun batchSize(batchSize: JsonField) = apply { this.batchSize = batchSize } - - /** Alias for calling [batchSize] with `BatchSize.ofString(string)`. */ - fun batchSize(string: String) = batchSize(BatchSize.ofString(string)) - - /** Alias for calling [batchSize] with `BatchSize.ofInteger(integer)`. */ - fun batchSize(integer: Long) = batchSize(BatchSize.ofInteger(integer)) - - fun learningRateMultiplier(learningRateMultiplier: LearningRateMultiplier?) = - learningRateMultiplier(JsonField.ofNullable(learningRateMultiplier)) - - /** - * Alias for calling [Builder.learningRateMultiplier] with - * `learningRateMultiplier.orElse(null)`. - */ - fun learningRateMultiplier(learningRateMultiplier: Optional) = - learningRateMultiplier(learningRateMultiplier.getOrNull()) - - /** - * Sets [Builder.learningRateMultiplier] to an arbitrary JSON value. - * - * You should usually call [Builder.learningRateMultiplier] with a well-typed - * [LearningRateMultiplier] value instead. This method is primarily for setting the - * field to an undocumented or not yet supported value. - */ - fun learningRateMultiplier(learningRateMultiplier: JsonField) = - apply { - this.learningRateMultiplier = learningRateMultiplier - } - - /** - * Alias for calling [learningRateMultiplier] with - * `LearningRateMultiplier.ofString(string)`. - */ - fun learningRateMultiplier(string: String) = - learningRateMultiplier(LearningRateMultiplier.ofString(string)) - - /** - * Alias for calling [learningRateMultiplier] with - * `LearningRateMultiplier.ofNumber(number)`. - */ - fun learningRateMultiplier(number: Double) = - learningRateMultiplier(LearningRateMultiplier.ofNumber(number)) - - fun nEpochs(nEpochs: NEpochs?) = nEpochs(JsonField.ofNullable(nEpochs)) - - /** Alias for calling [Builder.nEpochs] with `nEpochs.orElse(null)`. */ - fun nEpochs(nEpochs: Optional) = nEpochs(nEpochs.getOrNull()) - - /** - * Sets [Builder.nEpochs] to an arbitrary JSON value. - * - * You should usually call [Builder.nEpochs] with a well-typed [NEpochs] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun nEpochs(nEpochs: JsonField) = apply { this.nEpochs = nEpochs } - - /** Alias for calling [nEpochs] with `NEpochs.ofString(string)`. */ - fun nEpochs(string: String) = nEpochs(NEpochs.ofString(string)) - - /** Alias for calling [nEpochs] with `NEpochs.ofInteger(integer)`. */ - fun nEpochs(integer: Long) = nEpochs(NEpochs.ofInteger(integer)) - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [Hyperparameters]. - * - * Further updates to this [Builder] will not mutate the returned instance. - */ - fun build(): Hyperparameters = - Hyperparameters( - batchSize, - learningRateMultiplier, - nEpochs, - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): Hyperparameters = apply { - if (validated) { - return@apply - } - - batchSize().ifPresent { it.validate() } - learningRateMultiplier().ifPresent { it.validate() } - nEpochs().ifPresent { it.validate() } - validated = true - } - - @JsonDeserialize(using = BatchSize.Deserializer::class) - @JsonSerialize(using = BatchSize.Serializer::class) - class BatchSize - private constructor( - private val string: String? = null, - private val integer: Long? = null, - private val _json: JsonValue? = null, - ) { - - fun string(): Optional = Optional.ofNullable(string) - - fun integer(): Optional = Optional.ofNullable(integer) - - fun isString(): Boolean = string != null - - fun isInteger(): Boolean = integer != null - - fun asString(): String = string.getOrThrow("string") - - fun asInteger(): Long = integer.getOrThrow("integer") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { - string != null -> visitor.visitString(string) - integer != null -> visitor.visitInteger(integer) - else -> visitor.unknown(_json) - } - } - - private var validated: Boolean = false - - fun validate(): BatchSize = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitString(string: String) {} - - override fun visitInteger(integer: Long) {} - } - ) - validated = true - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is BatchSize && string == other.string && integer == other.integer /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, integer) /* spotless:on */ - - override fun toString(): String = - when { - string != null -> "BatchSize{string=$string}" - integer != null -> "BatchSize{integer=$integer}" - _json != null -> "BatchSize{_unknown=$_json}" - else -> throw IllegalStateException("Invalid BatchSize") - } - - companion object { - - @JvmStatic fun ofString(string: String) = BatchSize(string = string) - - @JvmStatic fun ofInteger(integer: Long) = BatchSize(integer = integer) - } - - /** - * An interface that defines how to map each variant of [BatchSize] to a value of type - * [T]. - */ - interface Visitor { - - fun visitString(string: String): T - - fun visitInteger(integer: Long): T - - /** - * Maps an unknown variant of [BatchSize] to a value of type [T]. - * - * An instance of [BatchSize] can contain an unknown variant if it was deserialized - * from data that doesn't match any known variant. For example, if the SDK is on an - * older version than the API, then the API may respond with new variants that the - * SDK is unaware of. - * - * @throws HanzoInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw HanzoInvalidDataException("Unknown BatchSize: $json") - } - } - - internal class Deserializer : BaseDeserializer(BatchSize::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): BatchSize { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return BatchSize(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return BatchSize(integer = it, _json = json) - } - - return BatchSize(_json = json) - } - } - - internal class Serializer : BaseSerializer(BatchSize::class) { - - override fun serialize( - value: BatchSize, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.string != null -> generator.writeObject(value.string) - value.integer != null -> generator.writeObject(value.integer) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid BatchSize") - } - } - } - } - - @JsonDeserialize(using = LearningRateMultiplier.Deserializer::class) - @JsonSerialize(using = LearningRateMultiplier.Serializer::class) - class LearningRateMultiplier - private constructor( - private val string: String? = null, - private val number: Double? = null, - private val _json: JsonValue? = null, - ) { - - fun string(): Optional = Optional.ofNullable(string) - - fun number(): Optional = Optional.ofNullable(number) - - fun isString(): Boolean = string != null - - fun isNumber(): Boolean = number != null - - fun asString(): String = string.getOrThrow("string") - - fun asNumber(): Double = number.getOrThrow("number") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { - string != null -> visitor.visitString(string) - number != null -> visitor.visitNumber(number) - else -> visitor.unknown(_json) - } - } - - private var validated: Boolean = false - - fun validate(): LearningRateMultiplier = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitString(string: String) {} - - override fun visitNumber(number: Double) {} - } - ) - validated = true - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is LearningRateMultiplier && string == other.string && number == other.number /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, number) /* spotless:on */ - - override fun toString(): String = - when { - string != null -> "LearningRateMultiplier{string=$string}" - number != null -> "LearningRateMultiplier{number=$number}" - _json != null -> "LearningRateMultiplier{_unknown=$_json}" - else -> throw IllegalStateException("Invalid LearningRateMultiplier") - } - - companion object { - - @JvmStatic fun ofString(string: String) = LearningRateMultiplier(string = string) - - @JvmStatic fun ofNumber(number: Double) = LearningRateMultiplier(number = number) - } - - /** - * An interface that defines how to map each variant of [LearningRateMultiplier] to a - * value of type [T]. - */ - interface Visitor { - - fun visitString(string: String): T - - fun visitNumber(number: Double): T - - /** - * Maps an unknown variant of [LearningRateMultiplier] to a value of type [T]. - * - * An instance of [LearningRateMultiplier] can contain an unknown variant if it was - * deserialized from data that doesn't match any known variant. For example, if the - * SDK is on an older version than the API, then the API may respond with new - * variants that the SDK is unaware of. - * - * @throws HanzoInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw HanzoInvalidDataException("Unknown LearningRateMultiplier: $json") - } - } - - internal class Deserializer : - BaseDeserializer(LearningRateMultiplier::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): LearningRateMultiplier { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return LearningRateMultiplier(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return LearningRateMultiplier(number = it, _json = json) - } - - return LearningRateMultiplier(_json = json) - } - } - - internal class Serializer : - BaseSerializer(LearningRateMultiplier::class) { - - override fun serialize( - value: LearningRateMultiplier, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.string != null -> generator.writeObject(value.string) - value.number != null -> generator.writeObject(value.number) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid LearningRateMultiplier") - } - } - } - } - - @JsonDeserialize(using = NEpochs.Deserializer::class) - @JsonSerialize(using = NEpochs.Serializer::class) - class NEpochs - private constructor( - private val string: String? = null, - private val integer: Long? = null, - private val _json: JsonValue? = null, - ) { - - fun string(): Optional = Optional.ofNullable(string) - - fun integer(): Optional = Optional.ofNullable(integer) - - fun isString(): Boolean = string != null - - fun isInteger(): Boolean = integer != null - - fun asString(): String = string.getOrThrow("string") - - fun asInteger(): Long = integer.getOrThrow("integer") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { - string != null -> visitor.visitString(string) - integer != null -> visitor.visitInteger(integer) - else -> visitor.unknown(_json) - } - } - - private var validated: Boolean = false - - fun validate(): NEpochs = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitString(string: String) {} - - override fun visitInteger(integer: Long) {} - } - ) - validated = true - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is NEpochs && string == other.string && integer == other.integer /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, integer) /* spotless:on */ - - override fun toString(): String = - when { - string != null -> "NEpochs{string=$string}" - integer != null -> "NEpochs{integer=$integer}" - _json != null -> "NEpochs{_unknown=$_json}" - else -> throw IllegalStateException("Invalid NEpochs") - } - - companion object { - - @JvmStatic fun ofString(string: String) = NEpochs(string = string) - - @JvmStatic fun ofInteger(integer: Long) = NEpochs(integer = integer) - } - - /** - * An interface that defines how to map each variant of [NEpochs] to a value of type - * [T]. - */ - interface Visitor { - - fun visitString(string: String): T - - fun visitInteger(integer: Long): T - - /** - * Maps an unknown variant of [NEpochs] to a value of type [T]. - * - * An instance of [NEpochs] can contain an unknown variant if it was deserialized - * from data that doesn't match any known variant. For example, if the SDK is on an - * older version than the API, then the API may respond with new variants that the - * SDK is unaware of. - * - * @throws HanzoInvalidDataException in the default implementation. - */ - fun unknown(json: JsonValue?): T { - throw HanzoInvalidDataException("Unknown NEpochs: $json") - } - } - - internal class Deserializer : BaseDeserializer(NEpochs::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): NEpochs { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return NEpochs(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return NEpochs(integer = it, _json = json) - } - - return NEpochs(_json = json) - } - } - - internal class Serializer : BaseSerializer(NEpochs::class) { - - override fun serialize( - value: NEpochs, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.string != null -> generator.writeObject(value.string) - value.integer != null -> generator.writeObject(value.integer) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid NEpochs") - } - } - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Hyperparameters && batchSize == other.batchSize && learningRateMultiplier == other.learningRateMultiplier && nEpochs == other.nEpochs && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(batchSize, learningRateMultiplier, nEpochs, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Hyperparameters{batchSize=$batchSize, learningRateMultiplier=$learningRateMultiplier, nEpochs=$nEpochs, additionalProperties=$additionalProperties}" - } - override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is JobCreateParams && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is JobCreateParams && + liteLlmFineTuningJobCreate == other.liteLlmFineTuningJobCreate && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(liteLlmFineTuningJobCreate, additionalHeaders, additionalQueryParams) override fun toString() = - "JobCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "JobCreateParams{liteLlmFineTuningJobCreate=$liteLlmFineTuningJobCreate, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobCreateResponse.kt index 5a6c64de..a871e0e1 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.finetuning.jobs import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class JobCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(after) + fun customLlmProvider(): Optional = Optional.ofNullable(customLlmProvider) + fun limit(): Optional = Optional.ofNullable(limit) + /** Comma separated list of model names to filter by. Example: 'gpt-4o,gpt-4o-mini' */ + fun targetModelNames(): Optional = Optional.ofNullable(targetModelNames) + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [JobListParams]. - * - * The following fields are required: - * ```java - * .customLlmProvider() - * ``` - */ + @JvmStatic fun none(): JobListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [JobListParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [JobListParams]. */ class Builder internal constructor() { - private var customLlmProvider: CustomLlmProvider? = null private var after: String? = null + private var customLlmProvider: CustomLlmProvider? = null private var limit: Long? = null + private var targetModelNames: String? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(jobListParams: JobListParams) = apply { - customLlmProvider = jobListParams.customLlmProvider after = jobListParams.after + customLlmProvider = jobListParams.customLlmProvider limit = jobListParams.limit + targetModelNames = jobListParams.targetModelNames additionalHeaders = jobListParams.additionalHeaders.toBuilder() additionalQueryParams = jobListParams.additionalQueryParams.toBuilder() } - fun customLlmProvider(customLlmProvider: CustomLlmProvider) = apply { - this.customLlmProvider = customLlmProvider - } - fun after(after: String?) = apply { this.after = after } /** Alias for calling [Builder.after] with `after.orElse(null)`. */ fun after(after: Optional) = after(after.getOrNull()) + fun customLlmProvider(customLlmProvider: CustomLlmProvider?) = apply { + this.customLlmProvider = customLlmProvider + } + + /** Alias for calling [Builder.customLlmProvider] with `customLlmProvider.orElse(null)`. */ + fun customLlmProvider(customLlmProvider: Optional) = + customLlmProvider(customLlmProvider.getOrNull()) + fun limit(limit: Long?) = apply { this.limit = limit } /** @@ -96,6 +102,15 @@ private constructor( /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ fun limit(limit: Optional) = limit(limit.getOrNull()) + /** Comma separated list of model names to filter by. Example: 'gpt-4o,gpt-4o-mini' */ + fun targetModelNames(targetModelNames: String?) = apply { + this.targetModelNames = targetModelNames + } + + /** Alias for calling [Builder.targetModelNames] with `targetModelNames.orElse(null)`. */ + fun targetModelNames(targetModelNames: Optional) = + targetModelNames(targetModelNames.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() putAllAdditionalHeaders(additionalHeaders) @@ -198,19 +213,13 @@ private constructor( * Returns an immutable instance of [JobListParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .customLlmProvider() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): JobListParams = JobListParams( - checkRequired("customLlmProvider", customLlmProvider), after, + customLlmProvider, limit, + targetModelNames, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -221,9 +230,10 @@ private constructor( override fun _queryParams(): QueryParams = QueryParams.builder() .apply { - put("custom_llm_provider", customLlmProvider.toString()) after?.let { put("after", it) } + customLlmProvider?.let { put("custom_llm_provider", it.toString()) } limit?.let { put("limit", it.toString()) } + targetModelNames?.let { put("target_model_names", it) } putAll(additionalQueryParams) } .build() @@ -316,12 +326,39 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): CustomLlmProvider = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is CustomLlmProvider && value == other.value /* spotless:on */ + return other is CustomLlmProvider && value == other.value } override fun hashCode() = value.hashCode() @@ -334,11 +371,25 @@ private constructor( return true } - return /* spotless:off */ other is JobListParams && customLlmProvider == other.customLlmProvider && after == other.after && limit == other.limit && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is JobListParams && + after == other.after && + customLlmProvider == other.customLlmProvider && + limit == other.limit && + targetModelNames == other.targetModelNames && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(customLlmProvider, after, limit, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + after, + customLlmProvider, + limit, + targetModelNames, + additionalHeaders, + additionalQueryParams, + ) override fun toString() = - "JobListParams{customLlmProvider=$customLlmProvider, after=$after, limit=$limit, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "JobListParams{after=$after, customLlmProvider=$customLlmProvider, limit=$limit, targetModelNames=$targetModelNames, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobListResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobListResponse.kt index 5f4ac553..1f342201 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobListResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobListResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.finetuning.jobs import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class JobListResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(fineTuningJobId) - fun customLlmProvider(): CustomLlmProvider = customLlmProvider + fun customLlmProvider(): Optional = Optional.ofNullable(customLlmProvider) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [JobRetrieveParams]. - * - * The following fields are required: - * ```java - * .fineTuningJobId() - * .customLlmProvider() - * ``` - */ + @JvmStatic fun none(): JobRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [JobRetrieveParams]. */ @JvmStatic fun builder() = Builder() } @@ -68,14 +65,22 @@ private constructor( additionalQueryParams = jobRetrieveParams.additionalQueryParams.toBuilder() } - fun fineTuningJobId(fineTuningJobId: String) = apply { + fun fineTuningJobId(fineTuningJobId: String?) = apply { this.fineTuningJobId = fineTuningJobId } - fun customLlmProvider(customLlmProvider: CustomLlmProvider) = apply { + /** Alias for calling [Builder.fineTuningJobId] with `fineTuningJobId.orElse(null)`. */ + fun fineTuningJobId(fineTuningJobId: Optional) = + fineTuningJobId(fineTuningJobId.getOrNull()) + + fun customLlmProvider(customLlmProvider: CustomLlmProvider?) = apply { this.customLlmProvider = customLlmProvider } + /** Alias for calling [Builder.customLlmProvider] with `customLlmProvider.orElse(null)`. */ + fun customLlmProvider(customLlmProvider: Optional) = + customLlmProvider(customLlmProvider.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() putAllAdditionalHeaders(additionalHeaders) @@ -178,19 +183,11 @@ private constructor( * Returns an immutable instance of [JobRetrieveParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .fineTuningJobId() - * .customLlmProvider() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): JobRetrieveParams = JobRetrieveParams( - checkRequired("fineTuningJobId", fineTuningJobId), - checkRequired("customLlmProvider", customLlmProvider), + fineTuningJobId, + customLlmProvider, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -198,7 +195,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { - 0 -> fineTuningJobId + 0 -> fineTuningJobId ?: "" else -> "" } @@ -207,7 +204,7 @@ private constructor( override fun _queryParams(): QueryParams = QueryParams.builder() .apply { - put("custom_llm_provider", customLlmProvider.toString()) + customLlmProvider?.let { put("custom_llm_provider", it.toString()) } putAll(additionalQueryParams) } .build() @@ -300,12 +297,39 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): CustomLlmProvider = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is CustomLlmProvider && value == other.value /* spotless:on */ + return other is CustomLlmProvider && value == other.value } override fun hashCode() = value.hashCode() @@ -318,10 +342,15 @@ private constructor( return true } - return /* spotless:off */ other is JobRetrieveParams && fineTuningJobId == other.fineTuningJobId && customLlmProvider == other.customLlmProvider && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is JobRetrieveParams && + fineTuningJobId == other.fineTuningJobId && + customLlmProvider == other.customLlmProvider && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(fineTuningJobId, customLlmProvider, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(fineTuningJobId, customLlmProvider, additionalHeaders, additionalQueryParams) override fun toString() = "JobRetrieveParams{fineTuningJobId=$fineTuningJobId, customLlmProvider=$customLlmProvider, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobRetrieveResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobRetrieveResponse.kt index d581a469..1d55a28a 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobRetrieveResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/JobRetrieveResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.finetuning.jobs import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class JobRetrieveResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, + private val trainingFile: JsonField, + private val customLlmProvider: JsonField, + private val hyperparameters: JsonField, + private val integrations: JsonField>, + private val seed: JsonField, + private val suffix: JsonField, + private val validationFile: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of(), + @JsonProperty("training_file") + @ExcludeMissing + trainingFile: JsonField = JsonMissing.of(), + @JsonProperty("custom_llm_provider") + @ExcludeMissing + customLlmProvider: JsonField = JsonMissing.of(), + @JsonProperty("hyperparameters") + @ExcludeMissing + hyperparameters: JsonField = JsonMissing.of(), + @JsonProperty("integrations") + @ExcludeMissing + integrations: JsonField> = JsonMissing.of(), + @JsonProperty("seed") @ExcludeMissing seed: JsonField = JsonMissing.of(), + @JsonProperty("suffix") @ExcludeMissing suffix: JsonField = JsonMissing.of(), + @JsonProperty("validation_file") + @ExcludeMissing + validationFile: JsonField = JsonMissing.of(), + ) : this( + model, + trainingFile, + customLlmProvider, + hyperparameters, + integrations, + seed, + suffix, + validationFile, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun model(): String = model.getRequired("model") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun trainingFile(): String = trainingFile.getRequired("training_file") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customLlmProvider(): Optional = + customLlmProvider.getOptional("custom_llm_provider") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun hyperparameters(): Optional = + hyperparameters.getOptional("hyperparameters") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun integrations(): Optional> = integrations.getOptional("integrations") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun seed(): Optional = seed.getOptional("seed") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun suffix(): Optional = suffix.getOptional("suffix") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun validationFile(): Optional = validationFile.getOptional("validation_file") + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + /** + * Returns the raw JSON value of [trainingFile]. + * + * Unlike [trainingFile], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("training_file") + @ExcludeMissing + fun _trainingFile(): JsonField = trainingFile + + /** + * Returns the raw JSON value of [customLlmProvider]. + * + * Unlike [customLlmProvider], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("custom_llm_provider") + @ExcludeMissing + fun _customLlmProvider(): JsonField = customLlmProvider + + /** + * Returns the raw JSON value of [hyperparameters]. + * + * Unlike [hyperparameters], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("hyperparameters") + @ExcludeMissing + fun _hyperparameters(): JsonField = hyperparameters + + /** + * Returns the raw JSON value of [integrations]. + * + * Unlike [integrations], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("integrations") + @ExcludeMissing + fun _integrations(): JsonField> = integrations + + /** + * Returns the raw JSON value of [seed]. + * + * Unlike [seed], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("seed") @ExcludeMissing fun _seed(): JsonField = seed + + /** + * Returns the raw JSON value of [suffix]. + * + * Unlike [suffix], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("suffix") @ExcludeMissing fun _suffix(): JsonField = suffix + + /** + * Returns the raw JSON value of [validationFile]. + * + * Unlike [validationFile], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("validation_file") + @ExcludeMissing + fun _validationFile(): JsonField = validationFile + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [LiteLlmFineTuningJobCreate]. + * + * The following fields are required: + * ```java + * .model() + * .trainingFile() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LiteLlmFineTuningJobCreate]. */ + class Builder internal constructor() { + + private var model: JsonField? = null + private var trainingFile: JsonField? = null + private var customLlmProvider: JsonField = JsonMissing.of() + private var hyperparameters: JsonField = JsonMissing.of() + private var integrations: JsonField>? = null + private var seed: JsonField = JsonMissing.of() + private var suffix: JsonField = JsonMissing.of() + private var validationFile: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(liteLlmFineTuningJobCreate: LiteLlmFineTuningJobCreate) = apply { + model = liteLlmFineTuningJobCreate.model + trainingFile = liteLlmFineTuningJobCreate.trainingFile + customLlmProvider = liteLlmFineTuningJobCreate.customLlmProvider + hyperparameters = liteLlmFineTuningJobCreate.hyperparameters + integrations = liteLlmFineTuningJobCreate.integrations.map { it.toMutableList() } + seed = liteLlmFineTuningJobCreate.seed + suffix = liteLlmFineTuningJobCreate.suffix + validationFile = liteLlmFineTuningJobCreate.validationFile + additionalProperties = liteLlmFineTuningJobCreate.additionalProperties.toMutableMap() + } + + fun model(model: String) = model(JsonField.of(model)) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun trainingFile(trainingFile: String) = trainingFile(JsonField.of(trainingFile)) + + /** + * Sets [Builder.trainingFile] to an arbitrary JSON value. + * + * You should usually call [Builder.trainingFile] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun trainingFile(trainingFile: JsonField) = apply { + this.trainingFile = trainingFile + } + + fun customLlmProvider(customLlmProvider: CustomLlmProvider?) = + customLlmProvider(JsonField.ofNullable(customLlmProvider)) + + /** Alias for calling [Builder.customLlmProvider] with `customLlmProvider.orElse(null)`. */ + fun customLlmProvider(customLlmProvider: Optional) = + customLlmProvider(customLlmProvider.getOrNull()) + + /** + * Sets [Builder.customLlmProvider] to an arbitrary JSON value. + * + * You should usually call [Builder.customLlmProvider] with a well-typed [CustomLlmProvider] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun customLlmProvider(customLlmProvider: JsonField) = apply { + this.customLlmProvider = customLlmProvider + } + + fun hyperparameters(hyperparameters: Hyperparameters?) = + hyperparameters(JsonField.ofNullable(hyperparameters)) + + /** Alias for calling [Builder.hyperparameters] with `hyperparameters.orElse(null)`. */ + fun hyperparameters(hyperparameters: Optional) = + hyperparameters(hyperparameters.getOrNull()) + + /** + * Sets [Builder.hyperparameters] to an arbitrary JSON value. + * + * You should usually call [Builder.hyperparameters] with a well-typed [Hyperparameters] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun hyperparameters(hyperparameters: JsonField) = apply { + this.hyperparameters = hyperparameters + } + + fun integrations(integrations: List?) = + integrations(JsonField.ofNullable(integrations)) + + /** Alias for calling [Builder.integrations] with `integrations.orElse(null)`. */ + fun integrations(integrations: Optional>) = + integrations(integrations.getOrNull()) + + /** + * Sets [Builder.integrations] to an arbitrary JSON value. + * + * You should usually call [Builder.integrations] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun integrations(integrations: JsonField>) = apply { + this.integrations = integrations.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [integrations]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addIntegration(integration: String) = apply { + integrations = + (integrations ?: JsonField.of(mutableListOf())).also { + checkKnown("integrations", it).add(integration) + } + } + + fun seed(seed: Long?) = seed(JsonField.ofNullable(seed)) + + /** + * Alias for [Builder.seed]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun seed(seed: Long) = seed(seed as Long?) + + /** Alias for calling [Builder.seed] with `seed.orElse(null)`. */ + fun seed(seed: Optional) = seed(seed.getOrNull()) + + /** + * Sets [Builder.seed] to an arbitrary JSON value. + * + * You should usually call [Builder.seed] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun seed(seed: JsonField) = apply { this.seed = seed } + + fun suffix(suffix: String?) = suffix(JsonField.ofNullable(suffix)) + + /** Alias for calling [Builder.suffix] with `suffix.orElse(null)`. */ + fun suffix(suffix: Optional) = suffix(suffix.getOrNull()) + + /** + * Sets [Builder.suffix] to an arbitrary JSON value. + * + * You should usually call [Builder.suffix] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun suffix(suffix: JsonField) = apply { this.suffix = suffix } + + fun validationFile(validationFile: String?) = + validationFile(JsonField.ofNullable(validationFile)) + + /** Alias for calling [Builder.validationFile] with `validationFile.orElse(null)`. */ + fun validationFile(validationFile: Optional) = + validationFile(validationFile.getOrNull()) + + /** + * Sets [Builder.validationFile] to an arbitrary JSON value. + * + * You should usually call [Builder.validationFile] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun validationFile(validationFile: JsonField) = apply { + this.validationFile = validationFile + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [LiteLlmFineTuningJobCreate]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .model() + * .trainingFile() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): LiteLlmFineTuningJobCreate = + LiteLlmFineTuningJobCreate( + checkRequired("model", model), + checkRequired("trainingFile", trainingFile), + customLlmProvider, + hyperparameters, + (integrations ?: JsonMissing.of()).map { it.toImmutable() }, + seed, + suffix, + validationFile, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): LiteLlmFineTuningJobCreate = apply { + if (validated) { + return@apply + } + + model() + trainingFile() + customLlmProvider().ifPresent { it.validate() } + hyperparameters().ifPresent { it.validate() } + integrations() + seed() + suffix() + validationFile() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (model.asKnown().isPresent) 1 else 0) + + (if (trainingFile.asKnown().isPresent) 1 else 0) + + (customLlmProvider.asKnown().getOrNull()?.validity() ?: 0) + + (hyperparameters.asKnown().getOrNull()?.validity() ?: 0) + + (integrations.asKnown().getOrNull()?.size ?: 0) + + (if (seed.asKnown().isPresent) 1 else 0) + + (if (suffix.asKnown().isPresent) 1 else 0) + + (if (validationFile.asKnown().isPresent) 1 else 0) + + class CustomLlmProvider @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val OPENAI = of("openai") + + @JvmField val AZURE = of("azure") + + @JvmField val VERTEX_AI = of("vertex_ai") + + @JvmStatic fun of(value: String) = CustomLlmProvider(JsonField.of(value)) + } + + /** An enum containing [CustomLlmProvider]'s known values. */ + enum class Known { + OPENAI, + AZURE, + VERTEX_AI, + } + + /** + * An enum containing [CustomLlmProvider]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [CustomLlmProvider] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + OPENAI, + AZURE, + VERTEX_AI, + /** + * An enum member indicating that [CustomLlmProvider] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + OPENAI -> Value.OPENAI + AZURE -> Value.AZURE + VERTEX_AI -> Value.VERTEX_AI + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + OPENAI -> Known.OPENAI + AZURE -> Known.AZURE + VERTEX_AI -> Known.VERTEX_AI + else -> throw HanzoInvalidDataException("Unknown CustomLlmProvider: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): CustomLlmProvider = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CustomLlmProvider && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class Hyperparameters + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val batchSize: JsonField, + private val learningRateMultiplier: JsonField, + private val nEpochs: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("batch_size") + @ExcludeMissing + batchSize: JsonField = JsonMissing.of(), + @JsonProperty("learning_rate_multiplier") + @ExcludeMissing + learningRateMultiplier: JsonField = JsonMissing.of(), + @JsonProperty("n_epochs") @ExcludeMissing nEpochs: JsonField = JsonMissing.of(), + ) : this(batchSize, learningRateMultiplier, nEpochs, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun batchSize(): Optional = batchSize.getOptional("batch_size") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun learningRateMultiplier(): Optional = + learningRateMultiplier.getOptional("learning_rate_multiplier") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun nEpochs(): Optional = nEpochs.getOptional("n_epochs") + + /** + * Returns the raw JSON value of [batchSize]. + * + * Unlike [batchSize], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("batch_size") + @ExcludeMissing + fun _batchSize(): JsonField = batchSize + + /** + * Returns the raw JSON value of [learningRateMultiplier]. + * + * Unlike [learningRateMultiplier], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("learning_rate_multiplier") + @ExcludeMissing + fun _learningRateMultiplier(): JsonField = learningRateMultiplier + + /** + * Returns the raw JSON value of [nEpochs]. + * + * Unlike [nEpochs], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("n_epochs") @ExcludeMissing fun _nEpochs(): JsonField = nEpochs + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Hyperparameters]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Hyperparameters]. */ + class Builder internal constructor() { + + private var batchSize: JsonField = JsonMissing.of() + private var learningRateMultiplier: JsonField = JsonMissing.of() + private var nEpochs: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(hyperparameters: Hyperparameters) = apply { + batchSize = hyperparameters.batchSize + learningRateMultiplier = hyperparameters.learningRateMultiplier + nEpochs = hyperparameters.nEpochs + additionalProperties = hyperparameters.additionalProperties.toMutableMap() + } + + fun batchSize(batchSize: BatchSize?) = batchSize(JsonField.ofNullable(batchSize)) + + /** Alias for calling [Builder.batchSize] with `batchSize.orElse(null)`. */ + fun batchSize(batchSize: Optional) = batchSize(batchSize.getOrNull()) + + /** + * Sets [Builder.batchSize] to an arbitrary JSON value. + * + * You should usually call [Builder.batchSize] with a well-typed [BatchSize] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun batchSize(batchSize: JsonField) = apply { this.batchSize = batchSize } + + /** Alias for calling [batchSize] with `BatchSize.ofString(string)`. */ + fun batchSize(string: String) = batchSize(BatchSize.ofString(string)) + + /** Alias for calling [batchSize] with `BatchSize.ofInteger(integer)`. */ + fun batchSize(integer: Long) = batchSize(BatchSize.ofInteger(integer)) + + fun learningRateMultiplier(learningRateMultiplier: LearningRateMultiplier?) = + learningRateMultiplier(JsonField.ofNullable(learningRateMultiplier)) + + /** + * Alias for calling [Builder.learningRateMultiplier] with + * `learningRateMultiplier.orElse(null)`. + */ + fun learningRateMultiplier(learningRateMultiplier: Optional) = + learningRateMultiplier(learningRateMultiplier.getOrNull()) + + /** + * Sets [Builder.learningRateMultiplier] to an arbitrary JSON value. + * + * You should usually call [Builder.learningRateMultiplier] with a well-typed + * [LearningRateMultiplier] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun learningRateMultiplier(learningRateMultiplier: JsonField) = + apply { + this.learningRateMultiplier = learningRateMultiplier + } + + /** + * Alias for calling [learningRateMultiplier] with + * `LearningRateMultiplier.ofString(string)`. + */ + fun learningRateMultiplier(string: String) = + learningRateMultiplier(LearningRateMultiplier.ofString(string)) + + /** + * Alias for calling [learningRateMultiplier] with + * `LearningRateMultiplier.ofNumber(number)`. + */ + fun learningRateMultiplier(number: Double) = + learningRateMultiplier(LearningRateMultiplier.ofNumber(number)) + + fun nEpochs(nEpochs: NEpochs?) = nEpochs(JsonField.ofNullable(nEpochs)) + + /** Alias for calling [Builder.nEpochs] with `nEpochs.orElse(null)`. */ + fun nEpochs(nEpochs: Optional) = nEpochs(nEpochs.getOrNull()) + + /** + * Sets [Builder.nEpochs] to an arbitrary JSON value. + * + * You should usually call [Builder.nEpochs] with a well-typed [NEpochs] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun nEpochs(nEpochs: JsonField) = apply { this.nEpochs = nEpochs } + + /** Alias for calling [nEpochs] with `NEpochs.ofString(string)`. */ + fun nEpochs(string: String) = nEpochs(NEpochs.ofString(string)) + + /** Alias for calling [nEpochs] with `NEpochs.ofInteger(integer)`. */ + fun nEpochs(integer: Long) = nEpochs(NEpochs.ofInteger(integer)) + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Hyperparameters]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Hyperparameters = + Hyperparameters( + batchSize, + learningRateMultiplier, + nEpochs, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Hyperparameters = apply { + if (validated) { + return@apply + } + + batchSize().ifPresent { it.validate() } + learningRateMultiplier().ifPresent { it.validate() } + nEpochs().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (batchSize.asKnown().getOrNull()?.validity() ?: 0) + + (learningRateMultiplier.asKnown().getOrNull()?.validity() ?: 0) + + (nEpochs.asKnown().getOrNull()?.validity() ?: 0) + + @JsonDeserialize(using = BatchSize.Deserializer::class) + @JsonSerialize(using = BatchSize.Serializer::class) + class BatchSize + private constructor( + private val string: String? = null, + private val integer: Long? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun integer(): Optional = Optional.ofNullable(integer) + + fun isString(): Boolean = string != null + + fun isInteger(): Boolean = integer != null + + fun asString(): String = string.getOrThrow("string") + + fun asInteger(): Long = integer.getOrThrow("integer") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + integer != null -> visitor.visitInteger(integer) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): BatchSize = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitInteger(integer: Long) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitInteger(integer: Long) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BatchSize && string == other.string && integer == other.integer + } + + override fun hashCode(): Int = Objects.hash(string, integer) + + override fun toString(): String = + when { + string != null -> "BatchSize{string=$string}" + integer != null -> "BatchSize{integer=$integer}" + _json != null -> "BatchSize{_unknown=$_json}" + else -> throw IllegalStateException("Invalid BatchSize") + } + + companion object { + + @JvmStatic fun ofString(string: String) = BatchSize(string = string) + + @JvmStatic fun ofInteger(integer: Long) = BatchSize(integer = integer) + } + + /** + * An interface that defines how to map each variant of [BatchSize] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitInteger(integer: Long): T + + /** + * Maps an unknown variant of [BatchSize] to a value of type [T]. + * + * An instance of [BatchSize] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the + * SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown BatchSize: $json") + } + } + + internal class Deserializer : BaseDeserializer(BatchSize::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): BatchSize { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + BatchSize(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + BatchSize(integer = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from boolean). + 0 -> BatchSize(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(BatchSize::class) { + + override fun serialize( + value: BatchSize, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.integer != null -> generator.writeObject(value.integer) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid BatchSize") + } + } + } + } + + @JsonDeserialize(using = LearningRateMultiplier.Deserializer::class) + @JsonSerialize(using = LearningRateMultiplier.Serializer::class) + class LearningRateMultiplier + private constructor( + private val string: String? = null, + private val number: Double? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun number(): Optional = Optional.ofNullable(number) + + fun isString(): Boolean = string != null + + fun isNumber(): Boolean = number != null + + fun asString(): String = string.getOrThrow("string") + + fun asNumber(): Double = number.getOrThrow("number") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + number != null -> visitor.visitNumber(number) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): LearningRateMultiplier = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitNumber(number: Double) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitNumber(number: Double) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is LearningRateMultiplier && + string == other.string && + number == other.number + } + + override fun hashCode(): Int = Objects.hash(string, number) + + override fun toString(): String = + when { + string != null -> "LearningRateMultiplier{string=$string}" + number != null -> "LearningRateMultiplier{number=$number}" + _json != null -> "LearningRateMultiplier{_unknown=$_json}" + else -> throw IllegalStateException("Invalid LearningRateMultiplier") + } + + companion object { + + @JvmStatic fun ofString(string: String) = LearningRateMultiplier(string = string) + + @JvmStatic fun ofNumber(number: Double) = LearningRateMultiplier(number = number) + } + + /** + * An interface that defines how to map each variant of [LearningRateMultiplier] to a + * value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitNumber(number: Double): T + + /** + * Maps an unknown variant of [LearningRateMultiplier] to a value of type [T]. + * + * An instance of [LearningRateMultiplier] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if the + * SDK is on an older version than the API, then the API may respond with new + * variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown LearningRateMultiplier: $json") + } + } + + internal class Deserializer : + BaseDeserializer(LearningRateMultiplier::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): LearningRateMultiplier { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + LearningRateMultiplier(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + LearningRateMultiplier(number = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from boolean). + 0 -> LearningRateMultiplier(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer(LearningRateMultiplier::class) { + + override fun serialize( + value: LearningRateMultiplier, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.number != null -> generator.writeObject(value.number) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid LearningRateMultiplier") + } + } + } + } + + @JsonDeserialize(using = NEpochs.Deserializer::class) + @JsonSerialize(using = NEpochs.Serializer::class) + class NEpochs + private constructor( + private val string: String? = null, + private val integer: Long? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun integer(): Optional = Optional.ofNullable(integer) + + fun isString(): Boolean = string != null + + fun isInteger(): Boolean = integer != null + + fun asString(): String = string.getOrThrow("string") + + fun asInteger(): Long = integer.getOrThrow("integer") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + integer != null -> visitor.visitInteger(integer) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): NEpochs = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitInteger(integer: Long) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitInteger(integer: Long) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is NEpochs && string == other.string && integer == other.integer + } + + override fun hashCode(): Int = Objects.hash(string, integer) + + override fun toString(): String = + when { + string != null -> "NEpochs{string=$string}" + integer != null -> "NEpochs{integer=$integer}" + _json != null -> "NEpochs{_unknown=$_json}" + else -> throw IllegalStateException("Invalid NEpochs") + } + + companion object { + + @JvmStatic fun ofString(string: String) = NEpochs(string = string) + + @JvmStatic fun ofInteger(integer: Long) = NEpochs(integer = integer) + } + + /** + * An interface that defines how to map each variant of [NEpochs] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitInteger(integer: Long): T + + /** + * Maps an unknown variant of [NEpochs] to a value of type [T]. + * + * An instance of [NEpochs] can contain an unknown variant if it was deserialized + * from data that doesn't match any known variant. For example, if the SDK is on an + * older version than the API, then the API may respond with new variants that the + * SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown NEpochs: $json") + } + } + + internal class Deserializer : BaseDeserializer(NEpochs::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): NEpochs { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + NEpochs(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + NEpochs(integer = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from boolean). + 0 -> NEpochs(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(NEpochs::class) { + + override fun serialize( + value: NEpochs, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.integer != null -> generator.writeObject(value.integer) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid NEpochs") + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Hyperparameters && + batchSize == other.batchSize && + learningRateMultiplier == other.learningRateMultiplier && + nEpochs == other.nEpochs && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(batchSize, learningRateMultiplier, nEpochs, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Hyperparameters{batchSize=$batchSize, learningRateMultiplier=$learningRateMultiplier, nEpochs=$nEpochs, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is LiteLlmFineTuningJobCreate && + model == other.model && + trainingFile == other.trainingFile && + customLlmProvider == other.customLlmProvider && + hyperparameters == other.hyperparameters && + integrations == other.integrations && + seed == other.seed && + suffix == other.suffix && + validationFile == other.validationFile && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + model, + trainingFile, + customLlmProvider, + hyperparameters, + integrations, + seed, + suffix, + validationFile, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "LiteLlmFineTuningJobCreate{model=$model, trainingFile=$trainingFile, customLlmProvider=$customLlmProvider, hyperparameters=$hyperparameters, integrations=$integrations, seed=$seed, suffix=$suffix, validationFile=$validationFile, additionalProperties=$additionalProperties}" +} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/cancel/CancelCreateParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/cancel/CancelCreateParams.kt index 0f1253fd..871a1ebf 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/cancel/CancelCreateParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/cancel/CancelCreateParams.kt @@ -4,12 +4,12 @@ package ai.hanzo.api.models.finetuning.jobs.cancel import ai.hanzo.api.core.JsonValue import ai.hanzo.api.core.Params -import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.http.Headers import ai.hanzo.api.core.http.QueryParams import ai.hanzo.api.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * Cancel a fine-tuning job. @@ -18,37 +18,35 @@ import java.util.Optional * https://api.openai.com/v1/fine_tuning/jobs/{fine_tuning_job_id}/cancel * * Supported Query Params: - * - `custom_llm_provider`: Name of the LLM provider + * - `custom_llm_provider`: Name of the LiteLLM provider * - `fine_tuning_job_id`: The ID of the fine-tuning job to cancel. */ class CancelCreateParams private constructor( - private val fineTuningJobId: String, + private val fineTuningJobId: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, private val additionalBodyProperties: Map, ) : Params { - fun fineTuningJobId(): String = fineTuningJobId + fun fineTuningJobId(): Optional = Optional.ofNullable(fineTuningJobId) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [CancelCreateParams]. - * - * The following fields are required: - * ```java - * .fineTuningJobId() - * ``` - */ + @JvmStatic fun none(): CancelCreateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [CancelCreateParams]. */ @JvmStatic fun builder() = Builder() } @@ -68,10 +66,14 @@ private constructor( additionalBodyProperties = cancelCreateParams.additionalBodyProperties.toMutableMap() } - fun fineTuningJobId(fineTuningJobId: String) = apply { + fun fineTuningJobId(fineTuningJobId: String?) = apply { this.fineTuningJobId = fineTuningJobId } + /** Alias for calling [Builder.fineTuningJobId] with `fineTuningJobId.orElse(null)`. */ + fun fineTuningJobId(fineTuningJobId: Optional) = + fineTuningJobId(fineTuningJobId.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() putAllAdditionalHeaders(additionalHeaders) @@ -196,30 +198,22 @@ private constructor( * Returns an immutable instance of [CancelCreateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .fineTuningJobId() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): CancelCreateParams = CancelCreateParams( - checkRequired("fineTuningJobId", fineTuningJobId), + fineTuningJobId, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> fineTuningJobId + 0 -> fineTuningJobId ?: "" else -> "" } @@ -232,10 +226,20 @@ private constructor( return true } - return /* spotless:off */ other is CancelCreateParams && fineTuningJobId == other.fineTuningJobId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is CancelCreateParams && + fineTuningJobId == other.fineTuningJobId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(fineTuningJobId, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + fineTuningJobId, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) override fun toString() = "CancelCreateParams{fineTuningJobId=$fineTuningJobId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/cancel/CancelCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/cancel/CancelCreateResponse.kt index 0ac70c28..b213b641 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/cancel/CancelCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/finetuning/jobs/cancel/CancelCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.finetuning.jobs.cancel import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class CancelCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [GeminiCreateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): GeminiCreateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [GeminiCreateParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = geminiCreateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [GeminiCreateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): GeminiCreateParams = GeminiCreateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is GeminiCreateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is GeminiCreateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "GeminiCreateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiCreateResponse.kt index a1ca57c9..9dd4505c 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.gemini import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class GeminiCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [GeminiDeleteParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): GeminiDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [GeminiDeleteParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = geminiDeleteParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [GeminiDeleteParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): GeminiDeleteParams = GeminiDeleteParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is GeminiDeleteParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is GeminiDeleteParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "GeminiDeleteParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiDeleteResponse.kt index 5e72b095..19c1d282 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.gemini import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class GeminiDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [GeminiPatchParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): GeminiPatchParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [GeminiPatchParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = geminiPatchParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [GeminiPatchParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): GeminiPatchParams = GeminiPatchParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is GeminiPatchParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is GeminiPatchParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "GeminiPatchParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiPatchResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiPatchResponse.kt index 82064a45..7d9187a5 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiPatchResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiPatchResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.gemini import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class GeminiPatchResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(endpoint) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [GeminiRetrieveParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): GeminiRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [GeminiRetrieveParams]. */ @JvmStatic fun builder() = Builder() } @@ -51,7 +49,10 @@ private constructor( additionalQueryParams = geminiRetrieveParams.additionalQueryParams.toBuilder() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -155,25 +156,14 @@ private constructor( * Returns an immutable instance of [GeminiRetrieveParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): GeminiRetrieveParams = - GeminiRetrieveParams( - checkRequired("endpoint", endpoint), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + GeminiRetrieveParams(endpoint, additionalHeaders.build(), additionalQueryParams.build()) } fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -186,10 +176,13 @@ private constructor( return true } - return /* spotless:off */ other is GeminiRetrieveParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is GeminiRetrieveParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(endpoint, additionalHeaders, additionalQueryParams) override fun toString() = "GeminiRetrieveParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiRetrieveResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiRetrieveResponse.kt index fa7d9413..e7b9398d 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiRetrieveResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiRetrieveResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.gemini import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class GeminiRetrieveResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [GeminiUpdateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): GeminiUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [GeminiUpdateParams]. */ @JvmStatic fun builder() = Builder() } @@ -59,7 +57,10 @@ private constructor( additionalBodyProperties = geminiUpdateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,30 +186,22 @@ private constructor( * Returns an immutable instance of [GeminiUpdateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): GeminiUpdateParams = GeminiUpdateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -221,10 +214,15 @@ private constructor( return true } - return /* spotless:off */ other is GeminiUpdateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is GeminiUpdateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "GeminiUpdateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiUpdateResponse.kt index ba7b3c9f..e7f40d7f 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/gemini/GeminiUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.gemini import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class GeminiUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(tags) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -221,10 +223,16 @@ private constructor( return true } - return /* spotless:off */ other is SpendListTagsParams && endDate == other.endDate && startDate == other.startDate && tags == other.tags && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is SpendListTagsParams && + endDate == other.endDate && + startDate == other.startDate && + tags == other.tags && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endDate, startDate, tags, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endDate, startDate, tags, additionalHeaders, additionalQueryParams) override fun toString() = "SpendListTagsParams{endDate=$endDate, startDate=$startDate, tags=$tags, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendListTagsResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendListTagsResponse.kt index 585b5b4b..3decd35e 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendListTagsResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendListTagsResponse.kt @@ -8,8 +8,10 @@ import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonField import ai.hanzo.api.core.JsonMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.core.allMaxBy import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.getOrThrow +import ai.hanzo.api.core.toImmutable import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter @@ -29,6 +31,7 @@ import java.util.Optional import kotlin.jvm.optionals.getOrNull class SpendListTagsResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val apiKey: JsonField, private val callType: JsonField, @@ -122,13 +125,13 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun endTime(): Optional = Optional.ofNullable(endTime.getNullable("endTime")) + fun endTime(): Optional = endTime.getOptional("endTime") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun messages(): Optional = Optional.ofNullable(messages.getNullable("messages")) + fun messages(): Optional = messages.getOptional("messages") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly @@ -140,54 +143,64 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun response(): Optional = Optional.ofNullable(response.getNullable("response")) + fun response(): Optional = response.getOptional("response") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun startTime(): Optional = Optional.ofNullable(startTime.getNullable("startTime")) + fun startTime(): Optional = startTime.getOptional("startTime") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun apiBase(): Optional = Optional.ofNullable(apiBase.getNullable("api_base")) + fun apiBase(): Optional = apiBase.getOptional("api_base") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun cacheHit(): Optional = Optional.ofNullable(cacheHit.getNullable("cache_hit")) + fun cacheHit(): Optional = cacheHit.getOptional("cache_hit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun cacheKey(): Optional = Optional.ofNullable(cacheKey.getNullable("cache_key")) + fun cacheKey(): Optional = cacheKey.getOptional("cache_key") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun completionTokens(): Optional = - Optional.ofNullable(completionTokens.getNullable("completion_tokens")) + fun completionTokens(): Optional = completionTokens.getOptional("completion_tokens") + /** + * This arbitrary value can be deserialized into a custom type using the `convert` method: + * ```java + * MyClass myObject = spendListTagsResponse.metadata().convert(MyClass.class); + * ``` + */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonValue = metadata /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun model(): Optional = Optional.ofNullable(model.getNullable("model")) + fun model(): Optional = model.getOptional("model") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun promptTokens(): Optional = - Optional.ofNullable(promptTokens.getNullable("prompt_tokens")) + fun promptTokens(): Optional = promptTokens.getOptional("prompt_tokens") + /** + * This arbitrary value can be deserialized into a custom type using the `convert` method: + * ```java + * MyClass myObject = spendListTagsResponse.requestTags().convert(MyClass.class); + * ``` + */ @JsonProperty("request_tags") @ExcludeMissing fun _requestTags(): JsonValue = requestTags /** @@ -195,25 +208,25 @@ private constructor( * server responded with an unexpected value). */ fun requesterIpAddress(): Optional = - Optional.ofNullable(requesterIpAddress.getNullable("requester_ip_address")) + requesterIpAddress.getOptional("requester_ip_address") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spend(): Optional = Optional.ofNullable(spend.getNullable("spend")) + fun spend(): Optional = spend.getOptional("spend") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun totalTokens(): Optional = Optional.ofNullable(totalTokens.getNullable("total_tokens")) + fun totalTokens(): Optional = totalTokens.getOptional("total_tokens") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun user(): Optional = Optional.ofNullable(user.getNullable("user")) + fun user(): Optional = user.getOptional("user") /** * Returns the raw JSON value of [apiKey]. @@ -481,8 +494,9 @@ private constructor( fun messagesOfJsonValues(jsonValues: List) = messages(Messages.ofJsonValues(jsonValues)) - /** Alias for calling [messages] with `Messages.ofJsonValue(jsonValue)`. */ - fun messages(jsonValue: JsonValue) = messages(Messages.ofJsonValue(jsonValue)) + /** Alias for calling [messages] with `Messages.ofUnionMember2(unionMember2)`. */ + fun messages(unionMember2: Messages.UnionMember2) = + messages(Messages.ofUnionMember2(unionMember2)) fun requestId(requestId: String) = requestId(JsonField.of(requestId)) @@ -516,8 +530,9 @@ private constructor( fun responseOfJsonValues(jsonValues: List) = response(Response.ofJsonValues(jsonValues)) - /** Alias for calling [response] with `Response.ofJsonValue(jsonValue)`. */ - fun response(jsonValue: JsonValue) = response(Response.ofJsonValue(jsonValue)) + /** Alias for calling [response] with `Response.ofUnionMember2(unionMember2)`. */ + fun response(unionMember2: Response.UnionMember2) = + response(Response.ofUnionMember2(unionMember2)) fun startTime(startTime: StartTime?) = startTime(JsonField.ofNullable(startTime)) @@ -804,6 +819,39 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (apiKey.asKnown().isPresent) 1 else 0) + + (if (callType.asKnown().isPresent) 1 else 0) + + (endTime.asKnown().getOrNull()?.validity() ?: 0) + + (messages.asKnown().getOrNull()?.validity() ?: 0) + + (if (requestId.asKnown().isPresent) 1 else 0) + + (response.asKnown().getOrNull()?.validity() ?: 0) + + (startTime.asKnown().getOrNull()?.validity() ?: 0) + + (if (apiBase.asKnown().isPresent) 1 else 0) + + (if (cacheHit.asKnown().isPresent) 1 else 0) + + (if (cacheKey.asKnown().isPresent) 1 else 0) + + (if (completionTokens.asKnown().isPresent) 1 else 0) + + (if (model.asKnown().isPresent) 1 else 0) + + (if (promptTokens.asKnown().isPresent) 1 else 0) + + (if (requesterIpAddress.asKnown().isPresent) 1 else 0) + + (if (spend.asKnown().isPresent) 1 else 0) + + (if (totalTokens.asKnown().isPresent) 1 else 0) + + (if (user.asKnown().isPresent) 1 else 0) + @JsonDeserialize(using = EndTime.Deserializer::class) @JsonSerialize(using = EndTime.Serializer::class) class EndTime @@ -827,13 +875,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) offsetDate != null -> visitor.visitOffsetDate(offsetDate) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -852,15 +899,41 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitOffsetDate(offsetDate: OffsetDateTime) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is EndTime && string == other.string && offsetDate == other.offsetDate /* spotless:on */ + return other is EndTime && string == other.string && offsetDate == other.offsetDate } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, offsetDate) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(string, offsetDate) override fun toString(): String = when { @@ -907,14 +980,28 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): EndTime { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return EndTime(string = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + EndTime(offsetDate = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + EndTime(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> EndTime(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() } - tryDeserialize(node, jacksonTypeRef())?.let { - return EndTime(offsetDate = it, _json = json) - } - - return EndTime(_json = json) } } @@ -941,7 +1028,7 @@ private constructor( private constructor( private val string: String? = null, private val jsonValues: List? = null, - private val jsonValue: JsonValue? = null, + private val unionMember2: UnionMember2? = null, private val _json: JsonValue? = null, ) { @@ -949,30 +1036,29 @@ private constructor( fun jsonValues(): Optional> = Optional.ofNullable(jsonValues) - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) + fun unionMember2(): Optional = Optional.ofNullable(unionMember2) fun isString(): Boolean = string != null fun isJsonValues(): Boolean = jsonValues != null - fun isJsonValue(): Boolean = jsonValue != null + fun isUnionMember2(): Boolean = unionMember2 != null fun asString(): String = string.getOrThrow("string") fun asJsonValues(): List = jsonValues.getOrThrow("jsonValues") - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") + fun asUnionMember2(): UnionMember2 = unionMember2.getOrThrow("unionMember2") fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) jsonValues != null -> visitor.visitJsonValues(jsonValues) - jsonValue != null -> visitor.visitJsonValue(jsonValue) + unionMember2 != null -> visitor.visitUnionMember2(unionMember2) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -987,27 +1073,61 @@ private constructor( override fun visitJsonValues(jsonValues: List) {} - override fun visitJsonValue(jsonValue: JsonValue) {} + override fun visitUnionMember2(unionMember2: UnionMember2) { + unionMember2.validate() + } } ) validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitJsonValues(jsonValues: List) = jsonValues.size + + override fun visitUnionMember2(unionMember2: UnionMember2) = + unionMember2.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Messages && string == other.string && jsonValues == other.jsonValues && jsonValue == other.jsonValue /* spotless:on */ + return other is Messages && + string == other.string && + jsonValues == other.jsonValues && + unionMember2 == other.unionMember2 } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, jsonValues, jsonValue) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(string, jsonValues, unionMember2) override fun toString(): String = when { string != null -> "Messages{string=$string}" jsonValues != null -> "Messages{jsonValues=$jsonValues}" - jsonValue != null -> "Messages{jsonValue=$jsonValue}" + unionMember2 != null -> "Messages{unionMember2=$unionMember2}" _json != null -> "Messages{_unknown=$_json}" else -> throw IllegalStateException("Invalid Messages") } @@ -1017,9 +1137,11 @@ private constructor( @JvmStatic fun ofString(string: String) = Messages(string = string) @JvmStatic - fun ofJsonValues(jsonValues: List) = Messages(jsonValues = jsonValues) + fun ofJsonValues(jsonValues: List) = + Messages(jsonValues = jsonValues.toImmutable()) - @JvmStatic fun ofJsonValue(jsonValue: JsonValue) = Messages(jsonValue = jsonValue) + @JvmStatic + fun ofUnionMember2(unionMember2: UnionMember2) = Messages(unionMember2 = unionMember2) } /** @@ -1031,7 +1153,7 @@ private constructor( fun visitJsonValues(jsonValues: List): T - fun visitJsonValue(jsonValue: JsonValue): T + fun visitUnionMember2(unionMember2: UnionMember2): T /** * Maps an unknown variant of [Messages] to a value of type [T]. @@ -1053,17 +1175,31 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Messages { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return Messages(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Messages(jsonValues = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return Messages(jsonValue = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Messages(unionMember2 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Messages(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Messages(jsonValues = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> Messages(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() } - - return Messages(_json = json) } } @@ -1077,12 +1213,114 @@ private constructor( when { value.string != null -> generator.writeObject(value.string) value.jsonValues != null -> generator.writeObject(value.jsonValues) - value.jsonValue != null -> generator.writeObject(value.jsonValue) + value.unionMember2 != null -> generator.writeObject(value.unionMember2) value._json != null -> generator.writeObject(value._json) else -> throw IllegalStateException("Invalid Messages") } } } + + class UnionMember2 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UnionMember2]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember2]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember2: UnionMember2) = apply { + additionalProperties = unionMember2.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UnionMember2 = UnionMember2(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember2 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember2 && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "UnionMember2{additionalProperties=$additionalProperties}" + } } @JsonDeserialize(using = Response.Deserializer::class) @@ -1091,7 +1329,7 @@ private constructor( private constructor( private val string: String? = null, private val jsonValues: List? = null, - private val jsonValue: JsonValue? = null, + private val unionMember2: UnionMember2? = null, private val _json: JsonValue? = null, ) { @@ -1099,30 +1337,29 @@ private constructor( fun jsonValues(): Optional> = Optional.ofNullable(jsonValues) - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) + fun unionMember2(): Optional = Optional.ofNullable(unionMember2) fun isString(): Boolean = string != null fun isJsonValues(): Boolean = jsonValues != null - fun isJsonValue(): Boolean = jsonValue != null + fun isUnionMember2(): Boolean = unionMember2 != null fun asString(): String = string.getOrThrow("string") fun asJsonValues(): List = jsonValues.getOrThrow("jsonValues") - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") + fun asUnionMember2(): UnionMember2 = unionMember2.getOrThrow("unionMember2") fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) jsonValues != null -> visitor.visitJsonValues(jsonValues) - jsonValue != null -> visitor.visitJsonValue(jsonValue) + unionMember2 != null -> visitor.visitUnionMember2(unionMember2) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1137,27 +1374,61 @@ private constructor( override fun visitJsonValues(jsonValues: List) {} - override fun visitJsonValue(jsonValue: JsonValue) {} + override fun visitUnionMember2(unionMember2: UnionMember2) { + unionMember2.validate() + } } ) validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitJsonValues(jsonValues: List) = jsonValues.size + + override fun visitUnionMember2(unionMember2: UnionMember2) = + unionMember2.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Response && string == other.string && jsonValues == other.jsonValues && jsonValue == other.jsonValue /* spotless:on */ + return other is Response && + string == other.string && + jsonValues == other.jsonValues && + unionMember2 == other.unionMember2 } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, jsonValues, jsonValue) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(string, jsonValues, unionMember2) override fun toString(): String = when { string != null -> "Response{string=$string}" jsonValues != null -> "Response{jsonValues=$jsonValues}" - jsonValue != null -> "Response{jsonValue=$jsonValue}" + unionMember2 != null -> "Response{unionMember2=$unionMember2}" _json != null -> "Response{_unknown=$_json}" else -> throw IllegalStateException("Invalid Response") } @@ -1167,9 +1438,11 @@ private constructor( @JvmStatic fun ofString(string: String) = Response(string = string) @JvmStatic - fun ofJsonValues(jsonValues: List) = Response(jsonValues = jsonValues) + fun ofJsonValues(jsonValues: List) = + Response(jsonValues = jsonValues.toImmutable()) - @JvmStatic fun ofJsonValue(jsonValue: JsonValue) = Response(jsonValue = jsonValue) + @JvmStatic + fun ofUnionMember2(unionMember2: UnionMember2) = Response(unionMember2 = unionMember2) } /** @@ -1181,7 +1454,7 @@ private constructor( fun visitJsonValues(jsonValues: List): T - fun visitJsonValue(jsonValue: JsonValue): T + fun visitUnionMember2(unionMember2: UnionMember2): T /** * Maps an unknown variant of [Response] to a value of type [T]. @@ -1203,17 +1476,31 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Response { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return Response(string = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Response(unionMember2 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Response(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Response(jsonValues = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> Response(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Response(jsonValues = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return Response(jsonValue = it, _json = json) - } - - return Response(_json = json) } } @@ -1227,12 +1514,114 @@ private constructor( when { value.string != null -> generator.writeObject(value.string) value.jsonValues != null -> generator.writeObject(value.jsonValues) - value.jsonValue != null -> generator.writeObject(value.jsonValue) + value.unionMember2 != null -> generator.writeObject(value.unionMember2) value._json != null -> generator.writeObject(value._json) else -> throw IllegalStateException("Invalid Response") } } } + + class UnionMember2 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UnionMember2]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember2]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember2: UnionMember2) = apply { + additionalProperties = unionMember2.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UnionMember2 = UnionMember2(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember2 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember2 && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "UnionMember2{additionalProperties=$additionalProperties}" + } } @JsonDeserialize(using = StartTime.Deserializer::class) @@ -1258,13 +1647,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) offsetDate != null -> visitor.visitOffsetDate(offsetDate) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1283,15 +1671,41 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitOffsetDate(offsetDate: OffsetDateTime) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is StartTime && string == other.string && offsetDate == other.offsetDate /* spotless:on */ + return other is StartTime && string == other.string && offsetDate == other.offsetDate } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, offsetDate) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(string, offsetDate) override fun toString(): String = when { @@ -1338,14 +1752,28 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): StartTime { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return StartTime(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return StartTime(offsetDate = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + StartTime(offsetDate = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + StartTime(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> StartTime(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() } - - return StartTime(_json = json) } } @@ -1371,12 +1799,53 @@ private constructor( return true } - return /* spotless:off */ other is SpendListTagsResponse && apiKey == other.apiKey && callType == other.callType && endTime == other.endTime && messages == other.messages && requestId == other.requestId && response == other.response && startTime == other.startTime && apiBase == other.apiBase && cacheHit == other.cacheHit && cacheKey == other.cacheKey && completionTokens == other.completionTokens && metadata == other.metadata && model == other.model && promptTokens == other.promptTokens && requestTags == other.requestTags && requesterIpAddress == other.requesterIpAddress && spend == other.spend && totalTokens == other.totalTokens && user == other.user && additionalProperties == other.additionalProperties /* spotless:on */ + return other is SpendListTagsResponse && + apiKey == other.apiKey && + callType == other.callType && + endTime == other.endTime && + messages == other.messages && + requestId == other.requestId && + response == other.response && + startTime == other.startTime && + apiBase == other.apiBase && + cacheHit == other.cacheHit && + cacheKey == other.cacheKey && + completionTokens == other.completionTokens && + metadata == other.metadata && + model == other.model && + promptTokens == other.promptTokens && + requestTags == other.requestTags && + requesterIpAddress == other.requesterIpAddress && + spend == other.spend && + totalTokens == other.totalTokens && + user == other.user && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(apiKey, callType, endTime, messages, requestId, response, startTime, apiBase, cacheHit, cacheKey, completionTokens, metadata, model, promptTokens, requestTags, requesterIpAddress, spend, totalTokens, user, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + apiKey, + callType, + endTime, + messages, + requestId, + response, + startTime, + apiBase, + cacheHit, + cacheKey, + completionTokens, + metadata, + model, + promptTokens, + requestTags, + requesterIpAddress, + spend, + totalTokens, + user, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendResetParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendResetParams.kt index 5a5d7da6..eb3710c7 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendResetParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendResetParams.kt @@ -13,10 +13,10 @@ import java.util.Optional /** * ADMIN ONLY / MASTER KEY Only Endpoint * - * Globally reset spend for All API Keys and Teams, maintain LLM_SpendLogs - * 1. LLM_SpendLogs will maintain the logs on spend, no data gets deleted from there - * 2. LLM_VerificationTokens spend will be set = 0 - * 3. LLM_TeamTable spend will be set = 0 + * Globally reset spend for All API Keys and Teams, maintain LiteLLM_SpendLogs + * 1. LiteLLM_SpendLogs will maintain the logs on spend, no data gets deleted from there + * 2. LiteLLM_VerificationTokens spend will be set = 0 + * 3. LiteLLM_TeamTable spend will be set = 0 */ class SpendResetParams private constructor( @@ -25,10 +25,13 @@ private constructor( private val additionalBodyProperties: Map, ) : Params { + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -188,8 +191,7 @@ private constructor( ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) override fun _headers(): Headers = additionalHeaders @@ -201,10 +203,14 @@ private constructor( return true } - return /* spotless:off */ other is SpendResetParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is SpendResetParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "SpendResetParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendResetResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendResetResponse.kt index 6a68750f..34aad01c 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendResetResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/global/spend/SpendResetResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.global.spend import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class SpendResetResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap EndTime(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() } - tryDeserialize(node, jacksonTypeRef())?.let { - return EndTime(offsetDate = it, _json = json) - } - - return EndTime(_json = json) } } @@ -941,7 +1028,7 @@ private constructor( private constructor( private val string: String? = null, private val jsonValues: List? = null, - private val jsonValue: JsonValue? = null, + private val unionMember2: UnionMember2? = null, private val _json: JsonValue? = null, ) { @@ -949,30 +1036,29 @@ private constructor( fun jsonValues(): Optional> = Optional.ofNullable(jsonValues) - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) + fun unionMember2(): Optional = Optional.ofNullable(unionMember2) fun isString(): Boolean = string != null fun isJsonValues(): Boolean = jsonValues != null - fun isJsonValue(): Boolean = jsonValue != null + fun isUnionMember2(): Boolean = unionMember2 != null fun asString(): String = string.getOrThrow("string") fun asJsonValues(): List = jsonValues.getOrThrow("jsonValues") - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") + fun asUnionMember2(): UnionMember2 = unionMember2.getOrThrow("unionMember2") fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) jsonValues != null -> visitor.visitJsonValues(jsonValues) - jsonValue != null -> visitor.visitJsonValue(jsonValue) + unionMember2 != null -> visitor.visitUnionMember2(unionMember2) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -987,27 +1073,61 @@ private constructor( override fun visitJsonValues(jsonValues: List) {} - override fun visitJsonValue(jsonValue: JsonValue) {} + override fun visitUnionMember2(unionMember2: UnionMember2) { + unionMember2.validate() + } } ) validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitJsonValues(jsonValues: List) = jsonValues.size + + override fun visitUnionMember2(unionMember2: UnionMember2) = + unionMember2.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Messages && string == other.string && jsonValues == other.jsonValues && jsonValue == other.jsonValue /* spotless:on */ + return other is Messages && + string == other.string && + jsonValues == other.jsonValues && + unionMember2 == other.unionMember2 } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, jsonValues, jsonValue) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(string, jsonValues, unionMember2) override fun toString(): String = when { string != null -> "Messages{string=$string}" jsonValues != null -> "Messages{jsonValues=$jsonValues}" - jsonValue != null -> "Messages{jsonValue=$jsonValue}" + unionMember2 != null -> "Messages{unionMember2=$unionMember2}" _json != null -> "Messages{_unknown=$_json}" else -> throw IllegalStateException("Invalid Messages") } @@ -1017,9 +1137,11 @@ private constructor( @JvmStatic fun ofString(string: String) = Messages(string = string) @JvmStatic - fun ofJsonValues(jsonValues: List) = Messages(jsonValues = jsonValues) + fun ofJsonValues(jsonValues: List) = + Messages(jsonValues = jsonValues.toImmutable()) - @JvmStatic fun ofJsonValue(jsonValue: JsonValue) = Messages(jsonValue = jsonValue) + @JvmStatic + fun ofUnionMember2(unionMember2: UnionMember2) = Messages(unionMember2 = unionMember2) } /** @@ -1031,7 +1153,7 @@ private constructor( fun visitJsonValues(jsonValues: List): T - fun visitJsonValue(jsonValue: JsonValue): T + fun visitUnionMember2(unionMember2: UnionMember2): T /** * Maps an unknown variant of [Messages] to a value of type [T]. @@ -1053,17 +1175,31 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Messages { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return Messages(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Messages(jsonValues = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return Messages(jsonValue = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Messages(unionMember2 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Messages(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Messages(jsonValues = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> Messages(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() } - - return Messages(_json = json) } } @@ -1077,12 +1213,114 @@ private constructor( when { value.string != null -> generator.writeObject(value.string) value.jsonValues != null -> generator.writeObject(value.jsonValues) - value.jsonValue != null -> generator.writeObject(value.jsonValue) + value.unionMember2 != null -> generator.writeObject(value.unionMember2) value._json != null -> generator.writeObject(value._json) else -> throw IllegalStateException("Invalid Messages") } } } + + class UnionMember2 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UnionMember2]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember2]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember2: UnionMember2) = apply { + additionalProperties = unionMember2.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UnionMember2 = UnionMember2(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember2 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember2 && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "UnionMember2{additionalProperties=$additionalProperties}" + } } @JsonDeserialize(using = Response.Deserializer::class) @@ -1091,7 +1329,7 @@ private constructor( private constructor( private val string: String? = null, private val jsonValues: List? = null, - private val jsonValue: JsonValue? = null, + private val unionMember2: UnionMember2? = null, private val _json: JsonValue? = null, ) { @@ -1099,30 +1337,29 @@ private constructor( fun jsonValues(): Optional> = Optional.ofNullable(jsonValues) - fun jsonValue(): Optional = Optional.ofNullable(jsonValue) + fun unionMember2(): Optional = Optional.ofNullable(unionMember2) fun isString(): Boolean = string != null fun isJsonValues(): Boolean = jsonValues != null - fun isJsonValue(): Boolean = jsonValue != null + fun isUnionMember2(): Boolean = unionMember2 != null fun asString(): String = string.getOrThrow("string") fun asJsonValues(): List = jsonValues.getOrThrow("jsonValues") - fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") + fun asUnionMember2(): UnionMember2 = unionMember2.getOrThrow("unionMember2") fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) jsonValues != null -> visitor.visitJsonValues(jsonValues) - jsonValue != null -> visitor.visitJsonValue(jsonValue) + unionMember2 != null -> visitor.visitUnionMember2(unionMember2) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1137,27 +1374,61 @@ private constructor( override fun visitJsonValues(jsonValues: List) {} - override fun visitJsonValue(jsonValue: JsonValue) {} + override fun visitUnionMember2(unionMember2: UnionMember2) { + unionMember2.validate() + } } ) validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitJsonValues(jsonValues: List) = jsonValues.size + + override fun visitUnionMember2(unionMember2: UnionMember2) = + unionMember2.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Response && string == other.string && jsonValues == other.jsonValues && jsonValue == other.jsonValue /* spotless:on */ + return other is Response && + string == other.string && + jsonValues == other.jsonValues && + unionMember2 == other.unionMember2 } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, jsonValues, jsonValue) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(string, jsonValues, unionMember2) override fun toString(): String = when { string != null -> "Response{string=$string}" jsonValues != null -> "Response{jsonValues=$jsonValues}" - jsonValue != null -> "Response{jsonValue=$jsonValue}" + unionMember2 != null -> "Response{unionMember2=$unionMember2}" _json != null -> "Response{_unknown=$_json}" else -> throw IllegalStateException("Invalid Response") } @@ -1167,9 +1438,11 @@ private constructor( @JvmStatic fun ofString(string: String) = Response(string = string) @JvmStatic - fun ofJsonValues(jsonValues: List) = Response(jsonValues = jsonValues) + fun ofJsonValues(jsonValues: List) = + Response(jsonValues = jsonValues.toImmutable()) - @JvmStatic fun ofJsonValue(jsonValue: JsonValue) = Response(jsonValue = jsonValue) + @JvmStatic + fun ofUnionMember2(unionMember2: UnionMember2) = Response(unionMember2 = unionMember2) } /** @@ -1181,7 +1454,7 @@ private constructor( fun visitJsonValues(jsonValues: List): T - fun visitJsonValue(jsonValue: JsonValue): T + fun visitUnionMember2(unionMember2: UnionMember2): T /** * Maps an unknown variant of [Response] to a value of type [T]. @@ -1203,17 +1476,31 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Response { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return Response(string = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Response(unionMember2 = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Response(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef>())?.let { + Response(jsonValues = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> Response(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Response(jsonValues = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return Response(jsonValue = it, _json = json) - } - - return Response(_json = json) } } @@ -1227,12 +1514,114 @@ private constructor( when { value.string != null -> generator.writeObject(value.string) value.jsonValues != null -> generator.writeObject(value.jsonValues) - value.jsonValue != null -> generator.writeObject(value.jsonValue) + value.unionMember2 != null -> generator.writeObject(value.unionMember2) value._json != null -> generator.writeObject(value._json) else -> throw IllegalStateException("Invalid Response") } } } + + class UnionMember2 + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UnionMember2]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnionMember2]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(unionMember2: UnionMember2) = apply { + additionalProperties = unionMember2.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UnionMember2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UnionMember2 = UnionMember2(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): UnionMember2 = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember2 && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "UnionMember2{additionalProperties=$additionalProperties}" + } } @JsonDeserialize(using = StartTime.Deserializer::class) @@ -1258,13 +1647,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) offsetDate != null -> visitor.visitOffsetDate(offsetDate) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1283,15 +1671,41 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitOffsetDate(offsetDate: OffsetDateTime) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is StartTime && string == other.string && offsetDate == other.offsetDate /* spotless:on */ + return other is StartTime && string == other.string && offsetDate == other.offsetDate } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, offsetDate) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(string, offsetDate) override fun toString(): String = when { @@ -1338,14 +1752,28 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): StartTime { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return StartTime(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return StartTime(offsetDate = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + StartTime(offsetDate = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + StartTime(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> StartTime(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() } - - return StartTime(_json = json) } } @@ -1371,12 +1799,53 @@ private constructor( return true } - return /* spotless:off */ other is SpendRetrieveReportResponse && apiKey == other.apiKey && callType == other.callType && endTime == other.endTime && messages == other.messages && requestId == other.requestId && response == other.response && startTime == other.startTime && apiBase == other.apiBase && cacheHit == other.cacheHit && cacheKey == other.cacheKey && completionTokens == other.completionTokens && metadata == other.metadata && model == other.model && promptTokens == other.promptTokens && requestTags == other.requestTags && requesterIpAddress == other.requesterIpAddress && spend == other.spend && totalTokens == other.totalTokens && user == other.user && additionalProperties == other.additionalProperties /* spotless:on */ + return other is SpendRetrieveReportResponse && + apiKey == other.apiKey && + callType == other.callType && + endTime == other.endTime && + messages == other.messages && + requestId == other.requestId && + response == other.response && + startTime == other.startTime && + apiBase == other.apiBase && + cacheHit == other.cacheHit && + cacheKey == other.cacheKey && + completionTokens == other.completionTokens && + metadata == other.metadata && + model == other.model && + promptTokens == other.promptTokens && + requestTags == other.requestTags && + requesterIpAddress == other.requesterIpAddress && + spend == other.spend && + totalTokens == other.totalTokens && + user == other.user && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(apiKey, callType, endTime, messages, requestId, response, startTime, apiBase, cacheHit, cacheKey, completionTokens, metadata, model, promptTokens, requestTags, requesterIpAddress, spend, totalTokens, user, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + apiKey, + callType, + endTime, + messages, + requestId, + response, + startTime, + apiBase, + cacheHit, + cacheKey, + completionTokens, + metadata, + model, + promptTokens, + requestTags, + requesterIpAddress, + spend, + totalTokens, + user, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/guardrails/GuardrailListParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/guardrails/GuardrailListParams.kt index e4df8254..29ac864a 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/guardrails/GuardrailListParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/guardrails/GuardrailListParams.kt @@ -10,7 +10,7 @@ import java.util.Objects /** * List the guardrails that are available on the proxy server * - * šŸ‘‰ [Guardrail docs](https://docs.hanzo.ai/docs/proxy/guardrails/quick_start) + * šŸ‘‰ [Guardrail docs](https://docs.litellm.ai/docs/proxy/guardrails/quick_start) * * Example Request: * ```bash @@ -20,24 +20,24 @@ import java.util.Objects * Example Response: * ```json * { - * "guardrails": [ - * { - * "guardrail_name": "bedrock-pre-guard", - * "guardrail_info": { - * "params": [ - * { - * "name": "toxicity_score", - * "type": "float", - * "description": "Score between 0-1 indicating content toxicity level" - * }, - * { - * "name": "pii_detection", - * "type": "boolean" - * } - * ] - * } - * } - * ] + * "guardrails": [ + * { + * "guardrail_name": "bedrock-pre-guard", + * "guardrail_info": { + * "params": [ + * { + * "name": "toxicity_score", + * "type": "float", + * "description": "Score between 0-1 indicating content toxicity level" + * }, + * { + * "name": "pii_detection", + * "type": "boolean" + * } + * ] + * } + * } + * ] * } * ``` */ @@ -47,8 +47,10 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -189,10 +191,12 @@ private constructor( return true } - return /* spotless:off */ other is GuardrailListParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is GuardrailListParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(additionalHeaders, additionalQueryParams) override fun toString() = "GuardrailListParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/guardrails/GuardrailListResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/guardrails/GuardrailListResponse.kt index 2e29ea9b..964ac072 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/guardrails/GuardrailListResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/guardrails/GuardrailListResponse.kt @@ -2,33 +2,27 @@ package ai.hanzo.api.models.guardrails -import ai.hanzo.api.core.BaseDeserializer -import ai.hanzo.api.core.BaseSerializer +import ai.hanzo.api.core.Enum import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonField import ai.hanzo.api.core.JsonMissing import ai.hanzo.api.core.JsonValue import ai.hanzo.api.core.checkKnown import ai.hanzo.api.core.checkRequired -import ai.hanzo.api.core.getOrThrow import ai.hanzo.api.core.toImmutable import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull class GuardrailListResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val guardrails: JsonField>, private val additionalProperties: MutableMap, @@ -167,30 +161,69 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (guardrails.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + class Guardrail + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - private val guardrailInfo: JsonValue, private val guardrailName: JsonField, - private val llmParams: JsonField, + private val createdAt: JsonField, + private val guardrailDefinitionLocation: JsonField, + private val guardrailId: JsonField, + private val guardrailInfo: JsonField, + private val litellmParams: JsonField, + private val updatedAt: JsonField, private val additionalProperties: MutableMap, ) { @JsonCreator private constructor( - @JsonProperty("guardrail_info") - @ExcludeMissing - guardrailInfo: JsonValue = JsonMissing.of(), @JsonProperty("guardrail_name") @ExcludeMissing guardrailName: JsonField = JsonMissing.of(), - @JsonProperty("llm_params") + @JsonProperty("created_at") @ExcludeMissing - llmParams: JsonField = JsonMissing.of(), - ) : this(guardrailInfo, guardrailName, llmParams, mutableMapOf()) - - @JsonProperty("guardrail_info") - @ExcludeMissing - fun _guardrailInfo(): JsonValue = guardrailInfo + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("guardrail_definition_location") + @ExcludeMissing + guardrailDefinitionLocation: JsonField = JsonMissing.of(), + @JsonProperty("guardrail_id") + @ExcludeMissing + guardrailId: JsonField = JsonMissing.of(), + @JsonProperty("guardrail_info") + @ExcludeMissing + guardrailInfo: JsonField = JsonMissing.of(), + @JsonProperty("litellm_params") + @ExcludeMissing + litellmParams: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") + @ExcludeMissing + updatedAt: JsonField = JsonMissing.of(), + ) : this( + guardrailName, + createdAt, + guardrailDefinitionLocation, + guardrailId, + guardrailInfo, + litellmParams, + updatedAt, + mutableMapOf(), + ) /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is @@ -199,12 +232,41 @@ private constructor( fun guardrailName(): String = guardrailName.getRequired("guardrail_name") /** - * The returned LLM Params object for /guardrails/list - * - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("created_at") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun guardrailDefinitionLocation(): Optional = + guardrailDefinitionLocation.getOptional("guardrail_definition_location") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun guardrailId(): Optional = guardrailId.getOptional("guardrail_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun guardrailInfo(): Optional = guardrailInfo.getOptional("guardrail_info") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun llmParams(): LlmParams = llmParams.getRequired("llm_params") + fun litellmParams(): Optional = litellmParams.getOptional("litellm_params") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") /** * Returns the raw JSON value of [guardrailName]. @@ -217,13 +279,62 @@ private constructor( fun _guardrailName(): JsonField = guardrailName /** - * Returns the raw JSON value of [llmParams]. + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [guardrailDefinitionLocation]. + * + * Unlike [guardrailDefinitionLocation], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("guardrail_definition_location") + @ExcludeMissing + fun _guardrailDefinitionLocation(): JsonField = + guardrailDefinitionLocation + + /** + * Returns the raw JSON value of [guardrailId]. + * + * Unlike [guardrailId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("guardrail_id") + @ExcludeMissing + fun _guardrailId(): JsonField = guardrailId + + /** + * Returns the raw JSON value of [guardrailInfo]. + * + * Unlike [guardrailInfo], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("guardrail_info") + @ExcludeMissing + fun _guardrailInfo(): JsonField = guardrailInfo + + /** + * Returns the raw JSON value of [litellmParams]. + * + * Unlike [litellmParams], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("litellm_params") + @ExcludeMissing + fun _litellmParams(): JsonField = litellmParams + + /** + * Returns the raw JSON value of [updatedAt]. * - * Unlike [llmParams], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("llm_params") + @JsonProperty("updated_at") @ExcludeMissing - fun _llmParams(): JsonField = llmParams + fun _updatedAt(): JsonField = updatedAt @JsonAnySetter private fun putAdditionalProperty(key: String, value: JsonValue) { @@ -244,9 +355,7 @@ private constructor( * * The following fields are required: * ```java - * .guardrailInfo() * .guardrailName() - * .llmParams() * ``` */ @JvmStatic fun builder() = Builder() @@ -255,23 +364,28 @@ private constructor( /** A builder for [Guardrail]. */ class Builder internal constructor() { - private var guardrailInfo: JsonValue? = null private var guardrailName: JsonField? = null - private var llmParams: JsonField? = null + private var createdAt: JsonField = JsonMissing.of() + private var guardrailDefinitionLocation: JsonField = + JsonMissing.of() + private var guardrailId: JsonField = JsonMissing.of() + private var guardrailInfo: JsonField = JsonMissing.of() + private var litellmParams: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(guardrail: Guardrail) = apply { - guardrailInfo = guardrail.guardrailInfo guardrailName = guardrail.guardrailName - llmParams = guardrail.llmParams + createdAt = guardrail.createdAt + guardrailDefinitionLocation = guardrail.guardrailDefinitionLocation + guardrailId = guardrail.guardrailId + guardrailInfo = guardrail.guardrailInfo + litellmParams = guardrail.litellmParams + updatedAt = guardrail.updatedAt additionalProperties = guardrail.additionalProperties.toMutableMap() } - fun guardrailInfo(guardrailInfo: JsonValue) = apply { - this.guardrailInfo = guardrailInfo - } - fun guardrailName(guardrailName: String) = guardrailName(JsonField.of(guardrailName)) /** @@ -285,17 +399,104 @@ private constructor( this.guardrailName = guardrailName } - /** The returned LLM Params object for /guardrails/list */ - fun llmParams(llmParams: LlmParams) = llmParams(JsonField.of(llmParams)) + fun createdAt(createdAt: OffsetDateTime?) = createdAt(JsonField.ofNullable(createdAt)) + + /** Alias for calling [Builder.createdAt] with `createdAt.orElse(null)`. */ + fun createdAt(createdAt: Optional) = createdAt(createdAt.getOrNull()) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { + this.createdAt = createdAt + } + + fun guardrailDefinitionLocation( + guardrailDefinitionLocation: GuardrailDefinitionLocation + ) = guardrailDefinitionLocation(JsonField.of(guardrailDefinitionLocation)) + + /** + * Sets [Builder.guardrailDefinitionLocation] to an arbitrary JSON value. + * + * You should usually call [Builder.guardrailDefinitionLocation] with a well-typed + * [GuardrailDefinitionLocation] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun guardrailDefinitionLocation( + guardrailDefinitionLocation: JsonField + ) = apply { this.guardrailDefinitionLocation = guardrailDefinitionLocation } + + fun guardrailId(guardrailId: String?) = guardrailId(JsonField.ofNullable(guardrailId)) + + /** Alias for calling [Builder.guardrailId] with `guardrailId.orElse(null)`. */ + fun guardrailId(guardrailId: Optional) = guardrailId(guardrailId.getOrNull()) + + /** + * Sets [Builder.guardrailId] to an arbitrary JSON value. + * + * You should usually call [Builder.guardrailId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun guardrailId(guardrailId: JsonField) = apply { + this.guardrailId = guardrailId + } + + fun guardrailInfo(guardrailInfo: GuardrailInfo?) = + guardrailInfo(JsonField.ofNullable(guardrailInfo)) + + /** Alias for calling [Builder.guardrailInfo] with `guardrailInfo.orElse(null)`. */ + fun guardrailInfo(guardrailInfo: Optional) = + guardrailInfo(guardrailInfo.getOrNull()) + + /** + * Sets [Builder.guardrailInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.guardrailInfo] with a well-typed [GuardrailInfo] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun guardrailInfo(guardrailInfo: JsonField) = apply { + this.guardrailInfo = guardrailInfo + } + + fun litellmParams(litellmParams: LitellmParams?) = + litellmParams(JsonField.ofNullable(litellmParams)) + + /** Alias for calling [Builder.litellmParams] with `litellmParams.orElse(null)`. */ + fun litellmParams(litellmParams: Optional) = + litellmParams(litellmParams.getOrNull()) + + /** + * Sets [Builder.litellmParams] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmParams] with a well-typed [LitellmParams] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun litellmParams(litellmParams: JsonField) = apply { + this.litellmParams = litellmParams + } + + fun updatedAt(updatedAt: OffsetDateTime?) = updatedAt(JsonField.ofNullable(updatedAt)) + + /** Alias for calling [Builder.updatedAt] with `updatedAt.orElse(null)`. */ + fun updatedAt(updatedAt: Optional) = updatedAt(updatedAt.getOrNull()) /** - * Sets [Builder.llmParams] to an arbitrary JSON value. + * Sets [Builder.updatedAt] to an arbitrary JSON value. * - * You should usually call [Builder.llmParams] with a well-typed [LlmParams] value + * You should usually call [Builder.updatedAt] with a well-typed [OffsetDateTime] value * instead. This method is primarily for setting the field to an undocumented or not yet * supported value. */ - fun llmParams(llmParams: JsonField) = apply { this.llmParams = llmParams } + fun updatedAt(updatedAt: JsonField) = apply { + this.updatedAt = updatedAt + } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() @@ -323,18 +524,20 @@ private constructor( * * The following fields are required: * ```java - * .guardrailInfo() * .guardrailName() - * .llmParams() * ``` * * @throws IllegalStateException if any required field is unset. */ fun build(): Guardrail = Guardrail( - checkRequired("guardrailInfo", guardrailInfo), checkRequired("guardrailName", guardrailName), - checkRequired("llmParams", llmParams), + createdAt, + guardrailDefinitionLocation, + guardrailId, + guardrailInfo, + litellmParams, + updatedAt, additionalProperties.toMutableMap(), ) } @@ -347,159 +550,205 @@ private constructor( } guardrailName() - llmParams().validate() + createdAt() + guardrailDefinitionLocation().ifPresent { it.validate() } + guardrailId() + guardrailInfo().ifPresent { it.validate() } + litellmParams().ifPresent { it.validate() } + updatedAt() validated = true } - /** The returned LLM Params object for /guardrails/list */ - class LlmParams - private constructor( - private val guardrail: JsonField, - private val mode: JsonField, - private val defaultOn: JsonField, - private val additionalProperties: MutableMap, - ) { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } - @JsonCreator - private constructor( - @JsonProperty("guardrail") - @ExcludeMissing - guardrail: JsonField = JsonMissing.of(), - @JsonProperty("mode") @ExcludeMissing mode: JsonField = JsonMissing.of(), - @JsonProperty("default_on") - @ExcludeMissing - defaultOn: JsonField = JsonMissing.of(), - ) : this(guardrail, mode, defaultOn, mutableMapOf()) + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (guardrailName.asKnown().isPresent) 1 else 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (guardrailDefinitionLocation.asKnown().getOrNull()?.validity() ?: 0) + + (if (guardrailId.asKnown().isPresent) 1 else 0) + + (guardrailInfo.asKnown().getOrNull()?.validity() ?: 0) + + (litellmParams.asKnown().getOrNull()?.validity() ?: 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + class GuardrailDefinitionLocation + @JsonCreator + private constructor(private val value: JsonField) : Enum { /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected - * value). + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. */ - fun guardrail(): String = guardrail.getRequired("guardrail") + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val DB = of("db") + + @JvmField val CONFIG = of("config") + + @JvmStatic fun of(value: String) = GuardrailDefinitionLocation(JsonField.of(value)) + } + + /** An enum containing [GuardrailDefinitionLocation]'s known values. */ + enum class Known { + DB, + CONFIG, + } /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is - * unexpectedly missing or null (e.g. if the server responded with an unexpected - * value). + * An enum containing [GuardrailDefinitionLocation]'s known values, as well as an + * [_UNKNOWN] member. + * + * An instance of [GuardrailDefinitionLocation] can contain an unknown value in a couple + * of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. */ - fun mode(): Mode = mode.getRequired("mode") + enum class Value { + DB, + CONFIG, + /** + * An enum member indicating that [GuardrailDefinitionLocation] was instantiated + * with an unknown value. + */ + _UNKNOWN, + } /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if - * the server responded with an unexpected value). + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. */ - fun defaultOn(): Optional = - Optional.ofNullable(defaultOn.getNullable("default_on")) + fun value(): Value = + when (this) { + DB -> Value.DB + CONFIG -> Value.CONFIG + else -> Value._UNKNOWN + } /** - * Returns the raw JSON value of [guardrail]. + * Returns an enum member corresponding to this class instance's value. * - * Unlike [guardrail], this method doesn't throw if the JSON field has an unexpected - * type. + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known + * member. */ - @JsonProperty("guardrail") - @ExcludeMissing - fun _guardrail(): JsonField = guardrail + fun known(): Known = + when (this) { + DB -> Known.DB + CONFIG -> Known.CONFIG + else -> + throw HanzoInvalidDataException( + "Unknown GuardrailDefinitionLocation: $value" + ) + } /** - * Returns the raw JSON value of [mode]. + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. * - * Unlike [mode], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. */ - @JsonProperty("mode") @ExcludeMissing fun _mode(): JsonField = mode + fun asString(): String = + _value().asString().orElseThrow { + HanzoInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): GuardrailDefinitionLocation = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } /** - * Returns the raw JSON value of [defaultOn]. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * Unlike [defaultOn], this method doesn't throw if the JSON field has an unexpected - * type. + * Used for best match union deserialization. */ - @JsonProperty("default_on") - @ExcludeMissing - fun _defaultOn(): JsonField = defaultOn + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GuardrailDefinitionLocation && value == other.value } + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class GuardrailInfo + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) + fun _additionalProperties(): Map = additionalProperties fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [LlmParams]. - * - * The following fields are required: - * ```java - * .guardrail() - * .mode() - * ``` - */ + /** Returns a mutable builder for constructing an instance of [GuardrailInfo]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [LlmParams]. */ + /** A builder for [GuardrailInfo]. */ class Builder internal constructor() { - private var guardrail: JsonField? = null - private var mode: JsonField? = null - private var defaultOn: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(llmParams: LlmParams) = apply { - guardrail = llmParams.guardrail - mode = llmParams.mode - defaultOn = llmParams.defaultOn - additionalProperties = llmParams.additionalProperties.toMutableMap() + internal fun from(guardrailInfo: GuardrailInfo) = apply { + additionalProperties = guardrailInfo.additionalProperties.toMutableMap() } - fun guardrail(guardrail: String) = guardrail(JsonField.of(guardrail)) - - /** - * Sets [Builder.guardrail] to an arbitrary JSON value. - * - * You should usually call [Builder.guardrail] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun guardrail(guardrail: JsonField) = apply { this.guardrail = guardrail } - - fun mode(mode: Mode) = mode(JsonField.of(mode)) - - /** - * Sets [Builder.mode] to an arbitrary JSON value. - * - * You should usually call [Builder.mode] with a well-typed [Mode] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun mode(mode: JsonField) = apply { this.mode = mode } - - /** Alias for calling [mode] with `Mode.ofString(string)`. */ - fun mode(string: String) = mode(Mode.ofString(string)) - - /** Alias for calling [mode] with `Mode.ofStrings(strings)`. */ - fun modeOfStrings(strings: List) = mode(Mode.ofStrings(strings)) - - fun defaultOn(defaultOn: Boolean) = defaultOn(JsonField.of(defaultOn)) - - /** - * Sets [Builder.defaultOn] to an arbitrary JSON value. - * - * You should usually call [Builder.defaultOn] with a well-typed [Boolean] value - * instead. This method is primarily for setting the field to an undocumented or not - * yet supported value. - */ - fun defaultOn(defaultOn: JsonField) = apply { this.defaultOn = defaultOn } - fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() putAllAdditionalProperties(additionalProperties) @@ -523,169 +772,1551 @@ private constructor( } /** - * Returns an immutable instance of [LlmParams]. + * Returns an immutable instance of [GuardrailInfo]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .guardrail() - * .mode() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ - fun build(): LlmParams = - LlmParams( - checkRequired("guardrail", guardrail), - checkRequired("mode", mode), - defaultOn, - additionalProperties.toMutableMap(), - ) + fun build(): GuardrailInfo = GuardrailInfo(additionalProperties.toImmutable()) } private var validated: Boolean = false - fun validate(): LlmParams = apply { + fun validate(): GuardrailInfo = apply { if (validated) { return@apply } - guardrail() - mode().validate() - defaultOn() validated = true } - @JsonDeserialize(using = Mode.Deserializer::class) - @JsonSerialize(using = Mode.Serializer::class) - class Mode - private constructor( - private val string: String? = null, - private val strings: List? = null, - private val _json: JsonValue? = null, - ) { - - fun string(): Optional = Optional.ofNullable(string) - - fun strings(): Optional> = Optional.ofNullable(strings) - - fun isString(): Boolean = string != null - - fun isStrings(): Boolean = strings != null - - fun asString(): String = string.getOrThrow("string") - - fun asStrings(): List = strings.getOrThrow("strings") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { - string != null -> visitor.visitString(string) - strings != null -> visitor.visitStrings(strings) - else -> visitor.unknown(_json) - } - } - - private var validated: Boolean = false - - fun validate(): Mode = apply { - if (validated) { - return@apply - } - - accept( - object : Visitor { - override fun visitString(string: String) {} - - override fun visitStrings(strings: List) {} - } - ) - validated = true + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } - return /* spotless:off */ other is Mode && string == other.string && strings == other.strings /* spotless:on */ + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, strings) /* spotless:on */ + return other is GuardrailInfo && additionalProperties == other.additionalProperties + } - override fun toString(): String = - when { - string != null -> "Mode{string=$string}" - strings != null -> "Mode{strings=$strings}" - _json != null -> "Mode{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Mode") - } + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - companion object { + override fun hashCode(): Int = hashCode - @JvmStatic fun ofString(string: String) = Mode(string = string) + override fun toString() = "GuardrailInfo{additionalProperties=$additionalProperties}" + } - @JvmStatic fun ofStrings(strings: List) = Mode(strings = strings) + class LitellmParams + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val additionalProviderSpecificParams: + JsonField, + private val apiBase: JsonField, + private val apiEndpoint: JsonField, + private val apiKey: JsonField, + private val categoryThresholds: JsonField, + private val credentials: JsonField, + private val defaultOn: JsonField, + private val detectSecretsConfig: JsonField, + private val experimentalUseLatestRoleMessageOnly: JsonField, + private val failOnError: JsonField, + private val guardName: JsonField, + private val location: JsonField, + private val maskRequestContent: JsonField, + private val maskResponseContent: JsonField, + private val model: JsonField, + private val pangeaInputRecipe: JsonField, + private val pangeaOutputRecipe: JsonField, + private val templateId: JsonField, + private val violationMessageTemplate: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("additional_provider_specific_params") + @ExcludeMissing + additionalProviderSpecificParams: JsonField = + JsonMissing.of(), + @JsonProperty("api_base") + @ExcludeMissing + apiBase: JsonField = JsonMissing.of(), + @JsonProperty("api_endpoint") + @ExcludeMissing + apiEndpoint: JsonField = JsonMissing.of(), + @JsonProperty("api_key") + @ExcludeMissing + apiKey: JsonField = JsonMissing.of(), + @JsonProperty("category_thresholds") + @ExcludeMissing + categoryThresholds: JsonField = JsonMissing.of(), + @JsonProperty("credentials") + @ExcludeMissing + credentials: JsonField = JsonMissing.of(), + @JsonProperty("default_on") + @ExcludeMissing + defaultOn: JsonField = JsonMissing.of(), + @JsonProperty("detect_secrets_config") + @ExcludeMissing + detectSecretsConfig: JsonField = JsonMissing.of(), + @JsonProperty("experimental_use_latest_role_message_only") + @ExcludeMissing + experimentalUseLatestRoleMessageOnly: JsonField = JsonMissing.of(), + @JsonProperty("fail_on_error") + @ExcludeMissing + failOnError: JsonField = JsonMissing.of(), + @JsonProperty("guard_name") + @ExcludeMissing + guardName: JsonField = JsonMissing.of(), + @JsonProperty("location") + @ExcludeMissing + location: JsonField = JsonMissing.of(), + @JsonProperty("mask_request_content") + @ExcludeMissing + maskRequestContent: JsonField = JsonMissing.of(), + @JsonProperty("mask_response_content") + @ExcludeMissing + maskResponseContent: JsonField = JsonMissing.of(), + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of(), + @JsonProperty("pangea_input_recipe") + @ExcludeMissing + pangeaInputRecipe: JsonField = JsonMissing.of(), + @JsonProperty("pangea_output_recipe") + @ExcludeMissing + pangeaOutputRecipe: JsonField = JsonMissing.of(), + @JsonProperty("template_id") + @ExcludeMissing + templateId: JsonField = JsonMissing.of(), + @JsonProperty("violation_message_template") + @ExcludeMissing + violationMessageTemplate: JsonField = JsonMissing.of(), + ) : this( + additionalProviderSpecificParams, + apiBase, + apiEndpoint, + apiKey, + categoryThresholds, + credentials, + defaultOn, + detectSecretsConfig, + experimentalUseLatestRoleMessageOnly, + failOnError, + guardName, + location, + maskRequestContent, + maskResponseContent, + model, + pangeaInputRecipe, + pangeaOutputRecipe, + templateId, + violationMessageTemplate, + mutableMapOf(), + ) + + /** + * Additional provider-specific parameters for generic guardrail APIs + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun additionalProviderSpecificParams(): Optional = + additionalProviderSpecificParams.getOptional("additional_provider_specific_params") + + /** + * Base URL for the guardrail service API + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun apiBase(): Optional = apiBase.getOptional("api_base") + + /** + * Optional custom API endpoint for Model Armor + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun apiEndpoint(): Optional = apiEndpoint.getOptional("api_endpoint") + + /** + * API key for the guardrail service + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun apiKey(): Optional = apiKey.getOptional("api_key") + + /** + * Threshold configuration for Lakera guardrail categories + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun categoryThresholds(): Optional = + categoryThresholds.getOptional("category_thresholds") + + /** + * Path to Google Cloud credentials JSON file or JSON string + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun credentials(): Optional = credentials.getOptional("credentials") + + /** + * Whether the guardrail is enabled by default + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun defaultOn(): Optional = defaultOn.getOptional("default_on") + + /** + * Configuration for detect-secrets guardrail + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun detectSecretsConfig(): Optional = + detectSecretsConfig.getOptional("detect_secrets_config") + + /** + * When True, guardrails only receive the latest message for the relevant role (e.g., + * newest user input pre-call, newest assistant output post-call) + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun experimentalUseLatestRoleMessageOnly(): Optional = + experimentalUseLatestRoleMessageOnly.getOptional( + "experimental_use_latest_role_message_only" + ) + + /** + * Whether to fail the request if Model Armor encounters an error + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun failOnError(): Optional = failOnError.getOptional("fail_on_error") + + /** + * Name of the guardrail in guardrails.ai + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun guardName(): Optional = guardName.getOptional("guard_name") + + /** + * Google Cloud location/region (e.g., us-central1) + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun location(): Optional = location.getOptional("location") + + /** + * Will mask request content if guardrail makes any changes + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun maskRequestContent(): Optional = + maskRequestContent.getOptional("mask_request_content") + + /** + * Will mask response content if guardrail makes any changes + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun maskResponseContent(): Optional = + maskResponseContent.getOptional("mask_response_content") + + /** + * Optional field if guardrail requires a 'model' parameter + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun model(): Optional = model.getOptional("model") + + /** + * Recipe for input (LLM request) + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun pangeaInputRecipe(): Optional = + pangeaInputRecipe.getOptional("pangea_input_recipe") + + /** + * Recipe for output (LLM response) + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun pangeaOutputRecipe(): Optional = + pangeaOutputRecipe.getOptional("pangea_output_recipe") + + /** + * The ID of your Model Armor template + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun templateId(): Optional = templateId.getOptional("template_id") + + /** + * Custom message when a guardrail blocks an action. Supports placeholders like + * {tool_name}, {rule_id}, and {default_message}. + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun violationMessageTemplate(): Optional = + violationMessageTemplate.getOptional("violation_message_template") + + /** + * Returns the raw JSON value of [additionalProviderSpecificParams]. + * + * Unlike [additionalProviderSpecificParams], this method doesn't throw if the JSON + * field has an unexpected type. + */ + @JsonProperty("additional_provider_specific_params") + @ExcludeMissing + fun _additionalProviderSpecificParams(): JsonField = + additionalProviderSpecificParams + + /** + * Returns the raw JSON value of [apiBase]. + * + * Unlike [apiBase], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_base") @ExcludeMissing fun _apiBase(): JsonField = apiBase + + /** + * Returns the raw JSON value of [apiEndpoint]. + * + * Unlike [apiEndpoint], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("api_endpoint") + @ExcludeMissing + fun _apiEndpoint(): JsonField = apiEndpoint + + /** + * Returns the raw JSON value of [apiKey]. + * + * Unlike [apiKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_key") @ExcludeMissing fun _apiKey(): JsonField = apiKey + + /** + * Returns the raw JSON value of [categoryThresholds]. + * + * Unlike [categoryThresholds], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("category_thresholds") + @ExcludeMissing + fun _categoryThresholds(): JsonField = categoryThresholds + + /** + * Returns the raw JSON value of [credentials]. + * + * Unlike [credentials], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("credentials") + @ExcludeMissing + fun _credentials(): JsonField = credentials + + /** + * Returns the raw JSON value of [defaultOn]. + * + * Unlike [defaultOn], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("default_on") + @ExcludeMissing + fun _defaultOn(): JsonField = defaultOn + + /** + * Returns the raw JSON value of [detectSecretsConfig]. + * + * Unlike [detectSecretsConfig], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("detect_secrets_config") + @ExcludeMissing + fun _detectSecretsConfig(): JsonField = detectSecretsConfig + + /** + * Returns the raw JSON value of [experimentalUseLatestRoleMessageOnly]. + * + * Unlike [experimentalUseLatestRoleMessageOnly], this method doesn't throw if the JSON + * field has an unexpected type. + */ + @JsonProperty("experimental_use_latest_role_message_only") + @ExcludeMissing + fun _experimentalUseLatestRoleMessageOnly(): JsonField = + experimentalUseLatestRoleMessageOnly + + /** + * Returns the raw JSON value of [failOnError]. + * + * Unlike [failOnError], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("fail_on_error") + @ExcludeMissing + fun _failOnError(): JsonField = failOnError + + /** + * Returns the raw JSON value of [guardName]. + * + * Unlike [guardName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("guard_name") + @ExcludeMissing + fun _guardName(): JsonField = guardName + + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("location") @ExcludeMissing fun _location(): JsonField = location + + /** + * Returns the raw JSON value of [maskRequestContent]. + * + * Unlike [maskRequestContent], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mask_request_content") + @ExcludeMissing + fun _maskRequestContent(): JsonField = maskRequestContent + + /** + * Returns the raw JSON value of [maskResponseContent]. + * + * Unlike [maskResponseContent], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mask_response_content") + @ExcludeMissing + fun _maskResponseContent(): JsonField = maskResponseContent + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + /** + * Returns the raw JSON value of [pangeaInputRecipe]. + * + * Unlike [pangeaInputRecipe], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("pangea_input_recipe") + @ExcludeMissing + fun _pangeaInputRecipe(): JsonField = pangeaInputRecipe + + /** + * Returns the raw JSON value of [pangeaOutputRecipe]. + * + * Unlike [pangeaOutputRecipe], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("pangea_output_recipe") + @ExcludeMissing + fun _pangeaOutputRecipe(): JsonField = pangeaOutputRecipe + + /** + * Returns the raw JSON value of [templateId]. + * + * Unlike [templateId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("template_id") + @ExcludeMissing + fun _templateId(): JsonField = templateId + + /** + * Returns the raw JSON value of [violationMessageTemplate]. + * + * Unlike [violationMessageTemplate], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("violation_message_template") + @ExcludeMissing + fun _violationMessageTemplate(): JsonField = violationMessageTemplate + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [LitellmParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LitellmParams]. */ + class Builder internal constructor() { + + private var additionalProviderSpecificParams: + JsonField = + JsonMissing.of() + private var apiBase: JsonField = JsonMissing.of() + private var apiEndpoint: JsonField = JsonMissing.of() + private var apiKey: JsonField = JsonMissing.of() + private var categoryThresholds: JsonField = JsonMissing.of() + private var credentials: JsonField = JsonMissing.of() + private var defaultOn: JsonField = JsonMissing.of() + private var detectSecretsConfig: JsonField = JsonMissing.of() + private var experimentalUseLatestRoleMessageOnly: JsonField = + JsonMissing.of() + private var failOnError: JsonField = JsonMissing.of() + private var guardName: JsonField = JsonMissing.of() + private var location: JsonField = JsonMissing.of() + private var maskRequestContent: JsonField = JsonMissing.of() + private var maskResponseContent: JsonField = JsonMissing.of() + private var model: JsonField = JsonMissing.of() + private var pangeaInputRecipe: JsonField = JsonMissing.of() + private var pangeaOutputRecipe: JsonField = JsonMissing.of() + private var templateId: JsonField = JsonMissing.of() + private var violationMessageTemplate: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(litellmParams: LitellmParams) = apply { + additionalProviderSpecificParams = + litellmParams.additionalProviderSpecificParams + apiBase = litellmParams.apiBase + apiEndpoint = litellmParams.apiEndpoint + apiKey = litellmParams.apiKey + categoryThresholds = litellmParams.categoryThresholds + credentials = litellmParams.credentials + defaultOn = litellmParams.defaultOn + detectSecretsConfig = litellmParams.detectSecretsConfig + experimentalUseLatestRoleMessageOnly = + litellmParams.experimentalUseLatestRoleMessageOnly + failOnError = litellmParams.failOnError + guardName = litellmParams.guardName + location = litellmParams.location + maskRequestContent = litellmParams.maskRequestContent + maskResponseContent = litellmParams.maskResponseContent + model = litellmParams.model + pangeaInputRecipe = litellmParams.pangeaInputRecipe + pangeaOutputRecipe = litellmParams.pangeaOutputRecipe + templateId = litellmParams.templateId + violationMessageTemplate = litellmParams.violationMessageTemplate + additionalProperties = litellmParams.additionalProperties.toMutableMap() + } + + /** Additional provider-specific parameters for generic guardrail APIs */ + fun additionalProviderSpecificParams( + additionalProviderSpecificParams: AdditionalProviderSpecificParams? + ) = + additionalProviderSpecificParams( + JsonField.ofNullable(additionalProviderSpecificParams) + ) + + /** + * Alias for calling [Builder.additionalProviderSpecificParams] with + * `additionalProviderSpecificParams.orElse(null)`. + */ + fun additionalProviderSpecificParams( + additionalProviderSpecificParams: Optional + ) = additionalProviderSpecificParams(additionalProviderSpecificParams.getOrNull()) + + /** + * Sets [Builder.additionalProviderSpecificParams] to an arbitrary JSON value. + * + * You should usually call [Builder.additionalProviderSpecificParams] with a + * well-typed [AdditionalProviderSpecificParams] value instead. This method is + * primarily for setting the field to an undocumented or not yet supported value. + */ + fun additionalProviderSpecificParams( + additionalProviderSpecificParams: JsonField + ) = apply { + this.additionalProviderSpecificParams = additionalProviderSpecificParams + } + + /** Base URL for the guardrail service API */ + fun apiBase(apiBase: String?) = apiBase(JsonField.ofNullable(apiBase)) + + /** Alias for calling [Builder.apiBase] with `apiBase.orElse(null)`. */ + fun apiBase(apiBase: Optional) = apiBase(apiBase.getOrNull()) + + /** + * Sets [Builder.apiBase] to an arbitrary JSON value. + * + * You should usually call [Builder.apiBase] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun apiBase(apiBase: JsonField) = apply { this.apiBase = apiBase } + + /** Optional custom API endpoint for Model Armor */ + fun apiEndpoint(apiEndpoint: String?) = + apiEndpoint(JsonField.ofNullable(apiEndpoint)) + + /** Alias for calling [Builder.apiEndpoint] with `apiEndpoint.orElse(null)`. */ + fun apiEndpoint(apiEndpoint: Optional) = + apiEndpoint(apiEndpoint.getOrNull()) + + /** + * Sets [Builder.apiEndpoint] to an arbitrary JSON value. + * + * You should usually call [Builder.apiEndpoint] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun apiEndpoint(apiEndpoint: JsonField) = apply { + this.apiEndpoint = apiEndpoint + } + + /** API key for the guardrail service */ + fun apiKey(apiKey: String?) = apiKey(JsonField.ofNullable(apiKey)) + + /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ + fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) + + /** + * Sets [Builder.apiKey] to an arbitrary JSON value. + * + * You should usually call [Builder.apiKey] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun apiKey(apiKey: JsonField) = apply { this.apiKey = apiKey } + + /** Threshold configuration for Lakera guardrail categories */ + fun categoryThresholds(categoryThresholds: CategoryThresholds?) = + categoryThresholds(JsonField.ofNullable(categoryThresholds)) + + /** + * Alias for calling [Builder.categoryThresholds] with + * `categoryThresholds.orElse(null)`. + */ + fun categoryThresholds(categoryThresholds: Optional) = + categoryThresholds(categoryThresholds.getOrNull()) + + /** + * Sets [Builder.categoryThresholds] to an arbitrary JSON value. + * + * You should usually call [Builder.categoryThresholds] with a well-typed + * [CategoryThresholds] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun categoryThresholds(categoryThresholds: JsonField) = apply { + this.categoryThresholds = categoryThresholds + } + + /** Path to Google Cloud credentials JSON file or JSON string */ + fun credentials(credentials: String?) = + credentials(JsonField.ofNullable(credentials)) + + /** Alias for calling [Builder.credentials] with `credentials.orElse(null)`. */ + fun credentials(credentials: Optional) = + credentials(credentials.getOrNull()) + + /** + * Sets [Builder.credentials] to an arbitrary JSON value. + * + * You should usually call [Builder.credentials] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun credentials(credentials: JsonField) = apply { + this.credentials = credentials + } + + /** Whether the guardrail is enabled by default */ + fun defaultOn(defaultOn: Boolean?) = defaultOn(JsonField.ofNullable(defaultOn)) + + /** + * Alias for [Builder.defaultOn]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun defaultOn(defaultOn: Boolean) = defaultOn(defaultOn as Boolean?) + + /** Alias for calling [Builder.defaultOn] with `defaultOn.orElse(null)`. */ + fun defaultOn(defaultOn: Optional) = defaultOn(defaultOn.getOrNull()) + + /** + * Sets [Builder.defaultOn] to an arbitrary JSON value. + * + * You should usually call [Builder.defaultOn] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun defaultOn(defaultOn: JsonField) = apply { this.defaultOn = defaultOn } + + /** Configuration for detect-secrets guardrail */ + fun detectSecretsConfig(detectSecretsConfig: DetectSecretsConfig?) = + detectSecretsConfig(JsonField.ofNullable(detectSecretsConfig)) + + /** + * Alias for calling [Builder.detectSecretsConfig] with + * `detectSecretsConfig.orElse(null)`. + */ + fun detectSecretsConfig(detectSecretsConfig: Optional) = + detectSecretsConfig(detectSecretsConfig.getOrNull()) + + /** + * Sets [Builder.detectSecretsConfig] to an arbitrary JSON value. + * + * You should usually call [Builder.detectSecretsConfig] with a well-typed + * [DetectSecretsConfig] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun detectSecretsConfig(detectSecretsConfig: JsonField) = + apply { + this.detectSecretsConfig = detectSecretsConfig + } + + /** + * When True, guardrails only receive the latest message for the relevant role + * (e.g., newest user input pre-call, newest assistant output post-call) + */ + fun experimentalUseLatestRoleMessageOnly( + experimentalUseLatestRoleMessageOnly: Boolean? + ) = + experimentalUseLatestRoleMessageOnly( + JsonField.ofNullable(experimentalUseLatestRoleMessageOnly) + ) + + /** + * Alias for [Builder.experimentalUseLatestRoleMessageOnly]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun experimentalUseLatestRoleMessageOnly( + experimentalUseLatestRoleMessageOnly: Boolean + ) = + experimentalUseLatestRoleMessageOnly( + experimentalUseLatestRoleMessageOnly as Boolean? + ) + + /** + * Alias for calling [Builder.experimentalUseLatestRoleMessageOnly] with + * `experimentalUseLatestRoleMessageOnly.orElse(null)`. + */ + fun experimentalUseLatestRoleMessageOnly( + experimentalUseLatestRoleMessageOnly: Optional + ) = + experimentalUseLatestRoleMessageOnly( + experimentalUseLatestRoleMessageOnly.getOrNull() + ) + + /** + * Sets [Builder.experimentalUseLatestRoleMessageOnly] to an arbitrary JSON value. + * + * You should usually call [Builder.experimentalUseLatestRoleMessageOnly] with a + * well-typed [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun experimentalUseLatestRoleMessageOnly( + experimentalUseLatestRoleMessageOnly: JsonField + ) = apply { + this.experimentalUseLatestRoleMessageOnly = experimentalUseLatestRoleMessageOnly + } + + /** Whether to fail the request if Model Armor encounters an error */ + fun failOnError(failOnError: Boolean?) = + failOnError(JsonField.ofNullable(failOnError)) + + /** + * Alias for [Builder.failOnError]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun failOnError(failOnError: Boolean) = failOnError(failOnError as Boolean?) + + /** Alias for calling [Builder.failOnError] with `failOnError.orElse(null)`. */ + fun failOnError(failOnError: Optional) = + failOnError(failOnError.getOrNull()) + + /** + * Sets [Builder.failOnError] to an arbitrary JSON value. + * + * You should usually call [Builder.failOnError] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun failOnError(failOnError: JsonField) = apply { + this.failOnError = failOnError + } + + /** Name of the guardrail in guardrails.ai */ + fun guardName(guardName: String?) = guardName(JsonField.ofNullable(guardName)) + + /** Alias for calling [Builder.guardName] with `guardName.orElse(null)`. */ + fun guardName(guardName: Optional) = guardName(guardName.getOrNull()) + + /** + * Sets [Builder.guardName] to an arbitrary JSON value. + * + * You should usually call [Builder.guardName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun guardName(guardName: JsonField) = apply { this.guardName = guardName } + + /** Google Cloud location/region (e.g., us-central1) */ + fun location(location: String?) = location(JsonField.ofNullable(location)) + + /** Alias for calling [Builder.location] with `location.orElse(null)`. */ + fun location(location: Optional) = location(location.getOrNull()) + + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun location(location: JsonField) = apply { this.location = location } + + /** Will mask request content if guardrail makes any changes */ + fun maskRequestContent(maskRequestContent: Boolean?) = + maskRequestContent(JsonField.ofNullable(maskRequestContent)) + + /** + * Alias for [Builder.maskRequestContent]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maskRequestContent(maskRequestContent: Boolean) = + maskRequestContent(maskRequestContent as Boolean?) + + /** + * Alias for calling [Builder.maskRequestContent] with + * `maskRequestContent.orElse(null)`. + */ + fun maskRequestContent(maskRequestContent: Optional) = + maskRequestContent(maskRequestContent.getOrNull()) + + /** + * Sets [Builder.maskRequestContent] to an arbitrary JSON value. + * + * You should usually call [Builder.maskRequestContent] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun maskRequestContent(maskRequestContent: JsonField) = apply { + this.maskRequestContent = maskRequestContent + } + + /** Will mask response content if guardrail makes any changes */ + fun maskResponseContent(maskResponseContent: Boolean?) = + maskResponseContent(JsonField.ofNullable(maskResponseContent)) + + /** + * Alias for [Builder.maskResponseContent]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maskResponseContent(maskResponseContent: Boolean) = + maskResponseContent(maskResponseContent as Boolean?) + + /** + * Alias for calling [Builder.maskResponseContent] with + * `maskResponseContent.orElse(null)`. + */ + fun maskResponseContent(maskResponseContent: Optional) = + maskResponseContent(maskResponseContent.getOrNull()) + + /** + * Sets [Builder.maskResponseContent] to an arbitrary JSON value. + * + * You should usually call [Builder.maskResponseContent] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun maskResponseContent(maskResponseContent: JsonField) = apply { + this.maskResponseContent = maskResponseContent + } + + /** Optional field if guardrail requires a 'model' parameter */ + fun model(model: String?) = model(JsonField.ofNullable(model)) + + /** Alias for calling [Builder.model] with `model.orElse(null)`. */ + fun model(model: Optional) = model(model.getOrNull()) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + /** Recipe for input (LLM request) */ + fun pangeaInputRecipe(pangeaInputRecipe: String?) = + pangeaInputRecipe(JsonField.ofNullable(pangeaInputRecipe)) + + /** + * Alias for calling [Builder.pangeaInputRecipe] with + * `pangeaInputRecipe.orElse(null)`. + */ + fun pangeaInputRecipe(pangeaInputRecipe: Optional) = + pangeaInputRecipe(pangeaInputRecipe.getOrNull()) + + /** + * Sets [Builder.pangeaInputRecipe] to an arbitrary JSON value. + * + * You should usually call [Builder.pangeaInputRecipe] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun pangeaInputRecipe(pangeaInputRecipe: JsonField) = apply { + this.pangeaInputRecipe = pangeaInputRecipe + } + + /** Recipe for output (LLM response) */ + fun pangeaOutputRecipe(pangeaOutputRecipe: String?) = + pangeaOutputRecipe(JsonField.ofNullable(pangeaOutputRecipe)) + + /** + * Alias for calling [Builder.pangeaOutputRecipe] with + * `pangeaOutputRecipe.orElse(null)`. + */ + fun pangeaOutputRecipe(pangeaOutputRecipe: Optional) = + pangeaOutputRecipe(pangeaOutputRecipe.getOrNull()) + + /** + * Sets [Builder.pangeaOutputRecipe] to an arbitrary JSON value. + * + * You should usually call [Builder.pangeaOutputRecipe] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun pangeaOutputRecipe(pangeaOutputRecipe: JsonField) = apply { + this.pangeaOutputRecipe = pangeaOutputRecipe + } + + /** The ID of your Model Armor template */ + fun templateId(templateId: String?) = templateId(JsonField.ofNullable(templateId)) + + /** Alias for calling [Builder.templateId] with `templateId.orElse(null)`. */ + fun templateId(templateId: Optional) = templateId(templateId.getOrNull()) + + /** + * Sets [Builder.templateId] to an arbitrary JSON value. + * + * You should usually call [Builder.templateId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun templateId(templateId: JsonField) = apply { + this.templateId = templateId + } + + /** + * Custom message when a guardrail blocks an action. Supports placeholders like + * {tool_name}, {rule_id}, and {default_message}. + */ + fun violationMessageTemplate(violationMessageTemplate: String?) = + violationMessageTemplate(JsonField.ofNullable(violationMessageTemplate)) + + /** + * Alias for calling [Builder.violationMessageTemplate] with + * `violationMessageTemplate.orElse(null)`. + */ + fun violationMessageTemplate(violationMessageTemplate: Optional) = + violationMessageTemplate(violationMessageTemplate.getOrNull()) + + /** + * Sets [Builder.violationMessageTemplate] to an arbitrary JSON value. + * + * You should usually call [Builder.violationMessageTemplate] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun violationMessageTemplate(violationMessageTemplate: JsonField) = apply { + this.violationMessageTemplate = violationMessageTemplate + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } /** - * An interface that defines how to map each variant of [Mode] to a value of type - * [T]. + * Returns an immutable instance of [LitellmParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. */ - interface Visitor { + fun build(): LitellmParams = + LitellmParams( + additionalProviderSpecificParams, + apiBase, + apiEndpoint, + apiKey, + categoryThresholds, + credentials, + defaultOn, + detectSecretsConfig, + experimentalUseLatestRoleMessageOnly, + failOnError, + guardName, + location, + maskRequestContent, + maskResponseContent, + model, + pangeaInputRecipe, + pangeaOutputRecipe, + templateId, + violationMessageTemplate, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): LitellmParams = apply { + if (validated) { + return@apply + } + + additionalProviderSpecificParams().ifPresent { it.validate() } + apiBase() + apiEndpoint() + apiKey() + categoryThresholds().ifPresent { it.validate() } + credentials() + defaultOn() + detectSecretsConfig().ifPresent { it.validate() } + experimentalUseLatestRoleMessageOnly() + failOnError() + guardName() + location() + maskRequestContent() + maskResponseContent() + model() + pangeaInputRecipe() + pangeaOutputRecipe() + templateId() + violationMessageTemplate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (additionalProviderSpecificParams.asKnown().getOrNull()?.validity() ?: 0) + + (if (apiBase.asKnown().isPresent) 1 else 0) + + (if (apiEndpoint.asKnown().isPresent) 1 else 0) + + (if (apiKey.asKnown().isPresent) 1 else 0) + + (categoryThresholds.asKnown().getOrNull()?.validity() ?: 0) + + (if (credentials.asKnown().isPresent) 1 else 0) + + (if (defaultOn.asKnown().isPresent) 1 else 0) + + (detectSecretsConfig.asKnown().getOrNull()?.validity() ?: 0) + + (if (experimentalUseLatestRoleMessageOnly.asKnown().isPresent) 1 else 0) + + (if (failOnError.asKnown().isPresent) 1 else 0) + + (if (guardName.asKnown().isPresent) 1 else 0) + + (if (location.asKnown().isPresent) 1 else 0) + + (if (maskRequestContent.asKnown().isPresent) 1 else 0) + + (if (maskResponseContent.asKnown().isPresent) 1 else 0) + + (if (model.asKnown().isPresent) 1 else 0) + + (if (pangeaInputRecipe.asKnown().isPresent) 1 else 0) + + (if (pangeaOutputRecipe.asKnown().isPresent) 1 else 0) + + (if (templateId.asKnown().isPresent) 1 else 0) + + (if (violationMessageTemplate.asKnown().isPresent) 1 else 0) + + /** Additional provider-specific parameters for generic guardrail APIs */ + class AdditionalProviderSpecificParams + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { - fun visitString(string: String): T + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) - fun visitStrings(strings: List): T + companion object { /** - * Maps an unknown variant of [Mode] to a value of type [T]. - * - * An instance of [Mode] can contain an unknown variant if it was deserialized - * from data that doesn't match any known variant. For example, if the SDK is on - * an older version than the API, then the API may respond with new variants - * that the SDK is unaware of. + * Returns a mutable builder for constructing an instance of + * [AdditionalProviderSpecificParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AdditionalProviderSpecificParams]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from( + additionalProviderSpecificParams: AdditionalProviderSpecificParams + ) = apply { + additionalProperties = + additionalProviderSpecificParams.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AdditionalProviderSpecificParams]. * - * @throws HanzoInvalidDataException in the default implementation. + * Further updates to this [Builder] will not mutate the returned instance. */ - fun unknown(json: JsonValue?): T { - throw HanzoInvalidDataException("Unknown Mode: $json") + fun build(): AdditionalProviderSpecificParams = + AdditionalProviderSpecificParams(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): AdditionalProviderSpecificParams = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } + + return other is AdditionalProviderSpecificParams && + additionalProperties == other.additionalProperties } - internal class Deserializer : BaseDeserializer(Mode::class) { + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - override fun ObjectCodec.deserialize(node: JsonNode): Mode { - val json = JsonValue.fromJsonNode(node) + override fun hashCode(): Int = hashCode - tryDeserialize(node, jacksonTypeRef())?.let { - return Mode(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Mode(strings = it, _json = json) + override fun toString() = + "AdditionalProviderSpecificParams{additionalProperties=$additionalProperties}" + } + + /** Threshold configuration for Lakera guardrail categories */ + class CategoryThresholds + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val jailbreak: JsonField, + private val promptInjection: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("jailbreak") + @ExcludeMissing + jailbreak: JsonField = JsonMissing.of(), + @JsonProperty("prompt_injection") + @ExcludeMissing + promptInjection: JsonField = JsonMissing.of(), + ) : this(jailbreak, promptInjection, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun jailbreak(): Optional = jailbreak.getOptional("jailbreak") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun promptInjection(): Optional = + promptInjection.getOptional("prompt_injection") + + /** + * Returns the raw JSON value of [jailbreak]. + * + * Unlike [jailbreak], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("jailbreak") + @ExcludeMissing + fun _jailbreak(): JsonField = jailbreak + + /** + * Returns the raw JSON value of [promptInjection]. + * + * Unlike [promptInjection], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("prompt_injection") + @ExcludeMissing + fun _promptInjection(): JsonField = promptInjection + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [CategoryThresholds]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CategoryThresholds]. */ + class Builder internal constructor() { + + private var jailbreak: JsonField = JsonMissing.of() + private var promptInjection: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(categoryThresholds: CategoryThresholds) = apply { + jailbreak = categoryThresholds.jailbreak + promptInjection = categoryThresholds.promptInjection + additionalProperties = + categoryThresholds.additionalProperties.toMutableMap() + } + + fun jailbreak(jailbreak: Double) = jailbreak(JsonField.of(jailbreak)) + + /** + * Sets [Builder.jailbreak] to an arbitrary JSON value. + * + * You should usually call [Builder.jailbreak] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun jailbreak(jailbreak: JsonField) = apply { + this.jailbreak = jailbreak + } + + fun promptInjection(promptInjection: Double) = + promptInjection(JsonField.of(promptInjection)) + + /** + * Sets [Builder.promptInjection] to an arbitrary JSON value. + * + * You should usually call [Builder.promptInjection] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun promptInjection(promptInjection: JsonField) = apply { + this.promptInjection = promptInjection + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) } - return Mode(_json = json) + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CategoryThresholds]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CategoryThresholds = + CategoryThresholds( + jailbreak, + promptInjection, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): CategoryThresholds = apply { + if (validated) { + return@apply + } + + jailbreak() + promptInjection() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (jailbreak.asKnown().isPresent) 1 else 0) + + (if (promptInjection.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } + + return other is CategoryThresholds && + jailbreak == other.jailbreak && + promptInjection == other.promptInjection && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(jailbreak, promptInjection, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CategoryThresholds{jailbreak=$jailbreak, promptInjection=$promptInjection, additionalProperties=$additionalProperties}" + } + + /** Configuration for detect-secrets guardrail */ + class DetectSecretsConfig + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [DetectSecretsConfig]. + */ + @JvmStatic fun builder() = Builder() } - internal class Serializer : BaseSerializer(Mode::class) { + /** A builder for [DetectSecretsConfig]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(detectSecretsConfig: DetectSecretsConfig) = apply { + additionalProperties = + detectSecretsConfig.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - override fun serialize( - value: Mode, - generator: JsonGenerator, - provider: SerializerProvider, - ) { - when { - value.string != null -> generator.writeObject(value.string) - value.strings != null -> generator.writeObject(value.strings) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Mode") + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [DetectSecretsConfig]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): DetectSecretsConfig = + DetectSecretsConfig(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): DetectSecretsConfig = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } + + return other is DetectSecretsConfig && + additionalProperties == other.additionalProperties } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "DetectSecretsConfig{additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { @@ -693,17 +2324,59 @@ private constructor( return true } - return /* spotless:off */ other is LlmParams && guardrail == other.guardrail && mode == other.mode && defaultOn == other.defaultOn && additionalProperties == other.additionalProperties /* spotless:on */ + return other is LitellmParams && + additionalProviderSpecificParams == other.additionalProviderSpecificParams && + apiBase == other.apiBase && + apiEndpoint == other.apiEndpoint && + apiKey == other.apiKey && + categoryThresholds == other.categoryThresholds && + credentials == other.credentials && + defaultOn == other.defaultOn && + detectSecretsConfig == other.detectSecretsConfig && + experimentalUseLatestRoleMessageOnly == + other.experimentalUseLatestRoleMessageOnly && + failOnError == other.failOnError && + guardName == other.guardName && + location == other.location && + maskRequestContent == other.maskRequestContent && + maskResponseContent == other.maskResponseContent && + model == other.model && + pangeaInputRecipe == other.pangeaInputRecipe && + pangeaOutputRecipe == other.pangeaOutputRecipe && + templateId == other.templateId && + violationMessageTemplate == other.violationMessageTemplate && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(guardrail, mode, defaultOn, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + additionalProviderSpecificParams, + apiBase, + apiEndpoint, + apiKey, + categoryThresholds, + credentials, + defaultOn, + detectSecretsConfig, + experimentalUseLatestRoleMessageOnly, + failOnError, + guardName, + location, + maskRequestContent, + maskResponseContent, + model, + pangeaInputRecipe, + pangeaOutputRecipe, + templateId, + violationMessageTemplate, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "LlmParams{guardrail=$guardrail, mode=$mode, defaultOn=$defaultOn, additionalProperties=$additionalProperties}" + "LitellmParams{additionalProviderSpecificParams=$additionalProviderSpecificParams, apiBase=$apiBase, apiEndpoint=$apiEndpoint, apiKey=$apiKey, categoryThresholds=$categoryThresholds, credentials=$credentials, defaultOn=$defaultOn, detectSecretsConfig=$detectSecretsConfig, experimentalUseLatestRoleMessageOnly=$experimentalUseLatestRoleMessageOnly, failOnError=$failOnError, guardName=$guardName, location=$location, maskRequestContent=$maskRequestContent, maskResponseContent=$maskResponseContent, model=$model, pangeaInputRecipe=$pangeaInputRecipe, pangeaOutputRecipe=$pangeaOutputRecipe, templateId=$templateId, violationMessageTemplate=$violationMessageTemplate, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { @@ -711,17 +2384,34 @@ private constructor( return true } - return /* spotless:off */ other is Guardrail && guardrailInfo == other.guardrailInfo && guardrailName == other.guardrailName && llmParams == other.llmParams && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Guardrail && + guardrailName == other.guardrailName && + createdAt == other.createdAt && + guardrailDefinitionLocation == other.guardrailDefinitionLocation && + guardrailId == other.guardrailId && + guardrailInfo == other.guardrailInfo && + litellmParams == other.litellmParams && + updatedAt == other.updatedAt && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(guardrailInfo, guardrailName, llmParams, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + guardrailName, + createdAt, + guardrailDefinitionLocation, + guardrailId, + guardrailInfo, + litellmParams, + updatedAt, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "Guardrail{guardrailInfo=$guardrailInfo, guardrailName=$guardrailName, llmParams=$llmParams, additionalProperties=$additionalProperties}" + "Guardrail{guardrailName=$guardrailName, createdAt=$createdAt, guardrailDefinitionLocation=$guardrailDefinitionLocation, guardrailId=$guardrailId, guardrailInfo=$guardrailInfo, litellmParams=$litellmParams, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { @@ -729,12 +2419,12 @@ private constructor( return true } - return /* spotless:off */ other is GuardrailListResponse && guardrails == other.guardrails && additionalProperties == other.additionalProperties /* spotless:on */ + return other is GuardrailListResponse && + guardrails == other.guardrails && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(guardrails, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckAllParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckAllParams.kt index ecba057c..26f71784 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckAllParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckAllParams.kt @@ -12,7 +12,7 @@ import kotlin.jvm.optionals.getOrNull /** * 🚨 USE `/health/liveliness` to health check the proxy 🚨 * - * See more šŸ‘‰ https://docs.hanzo.ai/docs/proxy/health + * See more šŸ‘‰ https://docs.litellm.ai/docs/proxy/health * * Check the health of all the endpoints in config.yaml * @@ -28,6 +28,7 @@ import kotlin.jvm.optionals.getOrNull class HealthCheckAllParams private constructor( private val model: String?, + private val modelId: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { @@ -35,8 +36,13 @@ private constructor( /** Specify the model name (optional) */ fun model(): Optional = Optional.ofNullable(model) + /** Specify the model ID (optional) */ + fun modelId(): Optional = Optional.ofNullable(modelId) + + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -53,12 +59,14 @@ private constructor( class Builder internal constructor() { private var model: String? = null + private var modelId: String? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(healthCheckAllParams: HealthCheckAllParams) = apply { model = healthCheckAllParams.model + modelId = healthCheckAllParams.modelId additionalHeaders = healthCheckAllParams.additionalHeaders.toBuilder() additionalQueryParams = healthCheckAllParams.additionalQueryParams.toBuilder() } @@ -69,6 +77,12 @@ private constructor( /** Alias for calling [Builder.model] with `model.orElse(null)`. */ fun model(model: Optional) = model(model.getOrNull()) + /** Specify the model ID (optional) */ + fun modelId(modelId: String?) = apply { this.modelId = modelId } + + /** Alias for calling [Builder.modelId] with `modelId.orElse(null)`. */ + fun modelId(modelId: Optional) = modelId(modelId.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() putAllAdditionalHeaders(additionalHeaders) @@ -173,7 +187,12 @@ private constructor( * Further updates to this [Builder] will not mutate the returned instance. */ fun build(): HealthCheckAllParams = - HealthCheckAllParams(model, additionalHeaders.build(), additionalQueryParams.build()) + HealthCheckAllParams( + model, + modelId, + additionalHeaders.build(), + additionalQueryParams.build(), + ) } override fun _headers(): Headers = additionalHeaders @@ -182,6 +201,7 @@ private constructor( QueryParams.builder() .apply { model?.let { put("model", it) } + modelId?.let { put("model_id", it) } putAll(additionalQueryParams) } .build() @@ -191,11 +211,16 @@ private constructor( return true } - return /* spotless:off */ other is HealthCheckAllParams && model == other.model && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is HealthCheckAllParams && + model == other.model && + modelId == other.modelId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(model, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(model, modelId, additionalHeaders, additionalQueryParams) override fun toString() = - "HealthCheckAllParams{model=$model, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "HealthCheckAllParams{model=$model, modelId=$modelId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckAllResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckAllResponse.kt index 122661e9..0b813d63 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckAllResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckAllResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.health import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class HealthCheckAllResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -84,17 +86,31 @@ private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap Value.SLACK_BUDGET_ALERTS LANGFUSE -> Value.LANGFUSE + LANGFUSE_OTEL -> Value.LANGFUSE_OTEL SLACK -> Value.SLACK OPENMETER -> Value.OPENMETER WEBHOOK -> Value.WEBHOOK EMAIL -> Value.EMAIL BRAINTRUST -> Value.BRAINTRUST DATADOG -> Value.DATADOG + GENERIC_API -> Value.GENERIC_API + ARIZE -> Value.ARIZE + SQS -> Value.SQS else -> Value._UNKNOWN } @@ -302,12 +324,16 @@ private constructor( when (this) { SLACK_BUDGET_ALERTS -> Known.SLACK_BUDGET_ALERTS LANGFUSE -> Known.LANGFUSE + LANGFUSE_OTEL -> Known.LANGFUSE_OTEL SLACK -> Known.SLACK OPENMETER -> Known.OPENMETER WEBHOOK -> Known.WEBHOOK EMAIL -> Known.EMAIL BRAINTRUST -> Known.BRAINTRUST DATADOG -> Known.DATADOG + GENERIC_API -> Known.GENERIC_API + ARIZE -> Known.ARIZE + SQS -> Known.SQS else -> throw HanzoInvalidDataException("Unknown Service: $value") } @@ -323,12 +349,39 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Service = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Service && value == other.value /* spotless:on */ + return other is Service && value == other.value } override fun hashCode() = value.hashCode() @@ -341,10 +394,13 @@ private constructor( return true } - return /* spotless:off */ other is HealthCheckServicesParams && service == other.service && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is HealthCheckServicesParams && + service == other.service && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(service, additionalHeaders, additionalQueryParams) override fun toString() = "HealthCheckServicesParams{service=$service, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckServicesResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckServicesResponse.kt index a5ea19f4..56c714a0 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckServicesResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/health/HealthCheckServicesResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.health import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class HealthCheckServicesResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -83,17 +85,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { + fun model(): Optional = Optional.ofNullable(model) + + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -37,18 +44,25 @@ private constructor( /** A builder for [GenerationCreateParams]. */ class Builder internal constructor() { + private var model: String? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(generationCreateParams: GenerationCreateParams) = apply { + model = generationCreateParams.model additionalHeaders = generationCreateParams.additionalHeaders.toBuilder() additionalQueryParams = generationCreateParams.additionalQueryParams.toBuilder() additionalBodyProperties = generationCreateParams.additionalBodyProperties.toMutableMap() } + fun model(model: String?) = apply { this.model = model } + + /** Alias for calling [Builder.model] with `model.orElse(null)`. */ + fun model(model: Optional) = model(model.getOrNull()) + fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() putAllAdditionalHeaders(additionalHeaders) @@ -176,30 +190,41 @@ private constructor( */ fun build(): GenerationCreateParams = GenerationCreateParams( + model, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) override fun _headers(): Headers = additionalHeaders - override fun _queryParams(): QueryParams = additionalQueryParams + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + model?.let { put("model", it) } + putAll(additionalQueryParams) + } + .build() override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is GenerationCreateParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is GenerationCreateParams && + model == other.model && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(model, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = - "GenerationCreateParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" + "GenerationCreateParams{model=$model, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/images/generations/GenerationCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/images/generations/GenerationCreateResponse.kt index dc1bda7d..468cd202 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/images/generations/GenerationCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/images/generations/GenerationCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.images.generations import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class GenerationCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, private val additionalProperties: MutableMap, @@ -132,17 +133,32 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (key.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is BlockKeyRequest && key == other.key && additionalProperties == other.additionalProperties /* spotless:on */ + return other is BlockKeyRequest && + key == other.key && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(key, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/GenerateKeyResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/GenerateKeyResponse.kt index 53d1ba5d..71936677 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/GenerateKeyResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/GenerateKeyResponse.kt @@ -2,6 +2,7 @@ package ai.hanzo.api.models.key +import ai.hanzo.api.core.Enum import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonField import ai.hanzo.api.core.JsonMissing @@ -21,37 +22,49 @@ import java.util.Optional import kotlin.jvm.optionals.getOrNull class GenerateKeyResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - private val expires: JsonField, private val key: JsonField, private val token: JsonField, - private val aliases: JsonValue, + private val aliases: JsonField, private val allowedCacheControls: JsonField>, + private val allowedPassthroughRoutes: JsonField>, + private val allowedRoutes: JsonField>, + private val allowedVectorStoreIndexes: JsonField>, private val blocked: JsonField, private val budgetDuration: JsonField, private val budgetId: JsonField, - private val config: JsonValue, + private val config: JsonField, + private val createdAt: JsonField, private val createdBy: JsonField, private val duration: JsonField, private val enforcedParams: JsonField>, + private val expires: JsonField, private val guardrails: JsonField>, private val keyAlias: JsonField, private val keyName: JsonField, - private val llmBudgetTable: JsonValue, + private val litellmBudgetTable: JsonValue, private val maxBudget: JsonField, private val maxParallelRequests: JsonField, - private val metadata: JsonValue, - private val modelMaxBudget: JsonValue, - private val modelRpmLimit: JsonValue, - private val modelTpmLimit: JsonValue, + private val metadata: JsonField, + private val modelMaxBudget: JsonField, + private val modelRpmLimit: JsonField, + private val modelTpmLimit: JsonField, private val models: JsonField>, - private val permissions: JsonValue, + private val objectPermission: JsonField, + private val organizationId: JsonField, + private val permissions: JsonField, + private val prompts: JsonField>, + private val routerSettings: JsonField, private val rpmLimit: JsonField, + private val rpmLimitType: JsonField, private val spend: JsonField, private val tags: JsonField>, private val teamId: JsonField, private val tokenId: JsonField, private val tpmLimit: JsonField, + private val tpmLimitType: JsonField, + private val updatedAt: JsonField, private val updatedBy: JsonField, private val userId: JsonField, private val additionalProperties: MutableMap, @@ -59,77 +72,116 @@ private constructor( @JsonCreator private constructor( - @JsonProperty("expires") - @ExcludeMissing - expires: JsonField = JsonMissing.of(), @JsonProperty("key") @ExcludeMissing key: JsonField = JsonMissing.of(), @JsonProperty("token") @ExcludeMissing token: JsonField = JsonMissing.of(), - @JsonProperty("aliases") @ExcludeMissing aliases: JsonValue = JsonMissing.of(), + @JsonProperty("aliases") @ExcludeMissing aliases: JsonField = JsonMissing.of(), @JsonProperty("allowed_cache_controls") @ExcludeMissing allowedCacheControls: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_passthrough_routes") + @ExcludeMissing + allowedPassthroughRoutes: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_routes") + @ExcludeMissing + allowedRoutes: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_vector_store_indexes") + @ExcludeMissing + allowedVectorStoreIndexes: JsonField> = JsonMissing.of(), @JsonProperty("blocked") @ExcludeMissing blocked: JsonField = JsonMissing.of(), @JsonProperty("budget_duration") @ExcludeMissing budgetDuration: JsonField = JsonMissing.of(), @JsonProperty("budget_id") @ExcludeMissing budgetId: JsonField = JsonMissing.of(), - @JsonProperty("config") @ExcludeMissing config: JsonValue = JsonMissing.of(), + @JsonProperty("config") @ExcludeMissing config: JsonField = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), @JsonProperty("created_by") @ExcludeMissing createdBy: JsonField = JsonMissing.of(), @JsonProperty("duration") @ExcludeMissing duration: JsonField = JsonMissing.of(), @JsonProperty("enforced_params") @ExcludeMissing enforcedParams: JsonField> = JsonMissing.of(), + @JsonProperty("expires") + @ExcludeMissing + expires: JsonField = JsonMissing.of(), @JsonProperty("guardrails") @ExcludeMissing guardrails: JsonField> = JsonMissing.of(), @JsonProperty("key_alias") @ExcludeMissing keyAlias: JsonField = JsonMissing.of(), @JsonProperty("key_name") @ExcludeMissing keyName: JsonField = JsonMissing.of(), - @JsonProperty("llm_budget_table") + @JsonProperty("litellm_budget_table") @ExcludeMissing - llmBudgetTable: JsonValue = JsonMissing.of(), + litellmBudgetTable: JsonValue = JsonMissing.of(), @JsonProperty("max_budget") @ExcludeMissing maxBudget: JsonField = JsonMissing.of(), @JsonProperty("max_parallel_requests") @ExcludeMissing maxParallelRequests: JsonField = JsonMissing.of(), - @JsonProperty("metadata") @ExcludeMissing metadata: JsonValue = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), @JsonProperty("model_max_budget") @ExcludeMissing - modelMaxBudget: JsonValue = JsonMissing.of(), + modelMaxBudget: JsonField = JsonMissing.of(), @JsonProperty("model_rpm_limit") @ExcludeMissing - modelRpmLimit: JsonValue = JsonMissing.of(), + modelRpmLimit: JsonField = JsonMissing.of(), @JsonProperty("model_tpm_limit") @ExcludeMissing - modelTpmLimit: JsonValue = JsonMissing.of(), + modelTpmLimit: JsonField = JsonMissing.of(), @JsonProperty("models") @ExcludeMissing models: JsonField> = JsonMissing.of(), - @JsonProperty("permissions") @ExcludeMissing permissions: JsonValue = JsonMissing.of(), + @JsonProperty("object_permission") + @ExcludeMissing + objectPermission: JsonField = JsonMissing.of(), + @JsonProperty("organization_id") + @ExcludeMissing + organizationId: JsonField = JsonMissing.of(), + @JsonProperty("permissions") + @ExcludeMissing + permissions: JsonField = JsonMissing.of(), + @JsonProperty("prompts") + @ExcludeMissing + prompts: JsonField> = JsonMissing.of(), + @JsonProperty("router_settings") + @ExcludeMissing + routerSettings: JsonField = JsonMissing.of(), @JsonProperty("rpm_limit") @ExcludeMissing rpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("rpm_limit_type") + @ExcludeMissing + rpmLimitType: JsonField = JsonMissing.of(), @JsonProperty("spend") @ExcludeMissing spend: JsonField = JsonMissing.of(), @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), @JsonProperty("team_id") @ExcludeMissing teamId: JsonField = JsonMissing.of(), @JsonProperty("token_id") @ExcludeMissing tokenId: JsonField = JsonMissing.of(), @JsonProperty("tpm_limit") @ExcludeMissing tpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("tpm_limit_type") + @ExcludeMissing + tpmLimitType: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") + @ExcludeMissing + updatedAt: JsonField = JsonMissing.of(), @JsonProperty("updated_by") @ExcludeMissing updatedBy: JsonField = JsonMissing.of(), @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), ) : this( - expires, key, token, aliases, allowedCacheControls, + allowedPassthroughRoutes, + allowedRoutes, + allowedVectorStoreIndexes, blocked, budgetDuration, budgetId, config, + createdAt, createdBy, duration, enforcedParams, + expires, guardrails, keyAlias, keyName, - llmBudgetTable, + litellmBudgetTable, maxBudget, maxParallelRequests, metadata, @@ -137,193 +189,293 @@ private constructor( modelRpmLimit, modelTpmLimit, models, + objectPermission, + organizationId, permissions, + prompts, + routerSettings, rpmLimit, + rpmLimitType, spend, tags, teamId, tokenId, tpmLimit, + tpmLimitType, + updatedAt, updatedBy, userId, mutableMapOf(), ) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun key(): String = key.getRequired("key") + /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun expires(): Optional = Optional.ofNullable(expires.getNullable("expires")) + fun token(): Optional = token.getOptional("token") /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly - * missing or null (e.g. if the server responded with an unexpected value). + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun key(): String = key.getRequired("key") + fun aliases(): Optional = aliases.getOptional("aliases") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun token(): Optional = Optional.ofNullable(token.getNullable("token")) + fun allowedCacheControls(): Optional> = + allowedCacheControls.getOptional("allowed_cache_controls") - @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonValue = aliases + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedPassthroughRoutes(): Optional> = + allowedPassthroughRoutes.getOptional("allowed_passthrough_routes") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun allowedCacheControls(): Optional> = - Optional.ofNullable(allowedCacheControls.getNullable("allowed_cache_controls")) + fun allowedRoutes(): Optional> = allowedRoutes.getOptional("allowed_routes") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedVectorStoreIndexes(): Optional> = + allowedVectorStoreIndexes.getOptional("allowed_vector_store_indexes") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun blocked(): Optional = blocked.getOptional("blocked") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun budgetDuration(): Optional = budgetDuration.getOptional("budget_duration") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun blocked(): Optional = Optional.ofNullable(blocked.getNullable("blocked")) + fun budgetId(): Optional = budgetId.getOptional("budget_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetDuration(): Optional = - Optional.ofNullable(budgetDuration.getNullable("budget_duration")) + fun config(): Optional = config.getOptional("config") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetId(): Optional = Optional.ofNullable(budgetId.getNullable("budget_id")) + fun createdAt(): Optional = createdAt.getOptional("created_at") - @JsonProperty("config") @ExcludeMissing fun _config(): JsonValue = config + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdBy(): Optional = createdBy.getOptional("created_by") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun createdBy(): Optional = Optional.ofNullable(createdBy.getNullable("created_by")) + fun duration(): Optional = duration.getOptional("duration") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun duration(): Optional = Optional.ofNullable(duration.getNullable("duration")) + fun enforcedParams(): Optional> = enforcedParams.getOptional("enforced_params") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun enforcedParams(): Optional> = - Optional.ofNullable(enforcedParams.getNullable("enforced_params")) + fun expires(): Optional = expires.getOptional("expires") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun guardrails(): Optional> = - Optional.ofNullable(guardrails.getNullable("guardrails")) + fun guardrails(): Optional> = guardrails.getOptional("guardrails") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun keyAlias(): Optional = Optional.ofNullable(keyAlias.getNullable("key_alias")) + fun keyAlias(): Optional = keyAlias.getOptional("key_alias") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun keyName(): Optional = Optional.ofNullable(keyName.getNullable("key_name")) + fun keyName(): Optional = keyName.getOptional("key_name") - @JsonProperty("llm_budget_table") + /** + * This arbitrary value can be deserialized into a custom type using the `convert` method: + * ```java + * MyClass myObject = generateKeyResponse.litellmBudgetTable().convert(MyClass.class); + * ``` + */ + @JsonProperty("litellm_budget_table") @ExcludeMissing - fun _llmBudgetTable(): JsonValue = llmBudgetTable + fun _litellmBudgetTable(): JsonValue = litellmBudgetTable /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun maxBudget(): Optional = Optional.ofNullable(maxBudget.getNullable("max_budget")) + fun maxBudget(): Optional = maxBudget.getOptional("max_budget") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun maxParallelRequests(): Optional = - Optional.ofNullable(maxParallelRequests.getNullable("max_parallel_requests")) + maxParallelRequests.getOptional("max_parallel_requests") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonValue = metadata + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelMaxBudget(): Optional = modelMaxBudget.getOptional("model_max_budget") - @JsonProperty("model_max_budget") - @ExcludeMissing - fun _modelMaxBudget(): JsonValue = modelMaxBudget + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelRpmLimit(): Optional = modelRpmLimit.getOptional("model_rpm_limit") - @JsonProperty("model_rpm_limit") @ExcludeMissing fun _modelRpmLimit(): JsonValue = modelRpmLimit + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelTpmLimit(): Optional = modelTpmLimit.getOptional("model_tpm_limit") - @JsonProperty("model_tpm_limit") @ExcludeMissing fun _modelTpmLimit(): JsonValue = modelTpmLimit + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun models(): Optional> = models.getOptional("models") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun models(): Optional> = Optional.ofNullable(models.getNullable("models")) + fun objectPermission(): Optional = + objectPermission.getOptional("object_permission") - @JsonProperty("permissions") @ExcludeMissing fun _permissions(): JsonValue = permissions + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun organizationId(): Optional = organizationId.getOptional("organization_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rpmLimit(): Optional = Optional.ofNullable(rpmLimit.getNullable("rpm_limit")) + fun permissions(): Optional = permissions.getOptional("permissions") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spend(): Optional = Optional.ofNullable(spend.getNullable("spend")) + fun prompts(): Optional> = prompts.getOptional("prompts") /** + * Set of params that you can modify via `router.update_settings()`. + * * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tags(): Optional> = Optional.ofNullable(tags.getNullable("tags")) + fun routerSettings(): Optional = routerSettings.getOptional("router_settings") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun teamId(): Optional = Optional.ofNullable(teamId.getNullable("team_id")) + fun rpmLimit(): Optional = rpmLimit.getOptional("rpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tokenId(): Optional = Optional.ofNullable(tokenId.getNullable("token_id")) + fun rpmLimitType(): Optional = rpmLimitType.getOptional("rpm_limit_type") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tpmLimit(): Optional = Optional.ofNullable(tpmLimit.getNullable("tpm_limit")) + fun spend(): Optional = spend.getOptional("spend") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun updatedBy(): Optional = Optional.ofNullable(updatedBy.getNullable("updated_by")) + fun tags(): Optional> = tags.getOptional("tags") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) + fun teamId(): Optional = teamId.getOptional("team_id") /** - * Returns the raw JSON value of [expires]. - * - * Unlike [expires], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("expires") @ExcludeMissing fun _expires(): JsonField = expires + fun tokenId(): Optional = tokenId.getOptional("token_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tpmLimit(): Optional = tpmLimit.getOptional("tpm_limit") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tpmLimitType(): Optional = tpmLimitType.getOptional("tpm_limit_type") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedBy(): Optional = updatedBy.getOptional("updated_by") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") /** * Returns the raw JSON value of [key]. @@ -339,6 +491,13 @@ private constructor( */ @JsonProperty("token") @ExcludeMissing fun _token(): JsonField = token + /** + * Returns the raw JSON value of [aliases]. + * + * Unlike [aliases], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonField = aliases + /** * Returns the raw JSON value of [allowedCacheControls]. * @@ -349,6 +508,36 @@ private constructor( @ExcludeMissing fun _allowedCacheControls(): JsonField> = allowedCacheControls + /** + * Returns the raw JSON value of [allowedPassthroughRoutes]. + * + * Unlike [allowedPassthroughRoutes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("allowed_passthrough_routes") + @ExcludeMissing + fun _allowedPassthroughRoutes(): JsonField> = allowedPassthroughRoutes + + /** + * Returns the raw JSON value of [allowedRoutes]. + * + * Unlike [allowedRoutes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("allowed_routes") + @ExcludeMissing + fun _allowedRoutes(): JsonField> = allowedRoutes + + /** + * Returns the raw JSON value of [allowedVectorStoreIndexes]. + * + * Unlike [allowedVectorStoreIndexes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("allowed_vector_store_indexes") + @ExcludeMissing + fun _allowedVectorStoreIndexes(): JsonField> = + allowedVectorStoreIndexes + /** * Returns the raw JSON value of [blocked]. * @@ -372,6 +561,22 @@ private constructor( */ @JsonProperty("budget_id") @ExcludeMissing fun _budgetId(): JsonField = budgetId + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config") @ExcludeMissing fun _config(): JsonField = config + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + /** * Returns the raw JSON value of [createdBy]. * @@ -395,6 +600,13 @@ private constructor( @ExcludeMissing fun _enforcedParams(): JsonField> = enforcedParams + /** + * Returns the raw JSON value of [expires]. + * + * Unlike [expires], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("expires") @ExcludeMissing fun _expires(): JsonField = expires + /** * Returns the raw JSON value of [guardrails]. * @@ -435,6 +647,40 @@ private constructor( @ExcludeMissing fun _maxParallelRequests(): JsonField = maxParallelRequests + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [modelMaxBudget]. + * + * Unlike [modelMaxBudget], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model_max_budget") + @ExcludeMissing + fun _modelMaxBudget(): JsonField = modelMaxBudget + + /** + * Returns the raw JSON value of [modelRpmLimit]. + * + * Unlike [modelRpmLimit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model_rpm_limit") + @ExcludeMissing + fun _modelRpmLimit(): JsonField = modelRpmLimit + + /** + * Returns the raw JSON value of [modelTpmLimit]. + * + * Unlike [modelTpmLimit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model_tpm_limit") + @ExcludeMissing + fun _modelTpmLimit(): JsonField = modelTpmLimit + /** * Returns the raw JSON value of [models]. * @@ -442,6 +688,50 @@ private constructor( */ @JsonProperty("models") @ExcludeMissing fun _models(): JsonField> = models + /** + * Returns the raw JSON value of [objectPermission]. + * + * Unlike [objectPermission], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("object_permission") + @ExcludeMissing + fun _objectPermission(): JsonField = objectPermission + + /** + * Returns the raw JSON value of [organizationId]. + * + * Unlike [organizationId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("organization_id") + @ExcludeMissing + fun _organizationId(): JsonField = organizationId + + /** + * Returns the raw JSON value of [permissions]. + * + * Unlike [permissions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permissions") + @ExcludeMissing + fun _permissions(): JsonField = permissions + + /** + * Returns the raw JSON value of [prompts]. + * + * Unlike [prompts], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prompts") @ExcludeMissing fun _prompts(): JsonField> = prompts + + /** + * Returns the raw JSON value of [routerSettings]. + * + * Unlike [routerSettings], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("router_settings") + @ExcludeMissing + fun _routerSettings(): JsonField = routerSettings + /** * Returns the raw JSON value of [rpmLimit]. * @@ -449,6 +739,15 @@ private constructor( */ @JsonProperty("rpm_limit") @ExcludeMissing fun _rpmLimit(): JsonField = rpmLimit + /** + * Returns the raw JSON value of [rpmLimitType]. + * + * Unlike [rpmLimitType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("rpm_limit_type") + @ExcludeMissing + fun _rpmLimitType(): JsonField = rpmLimitType + /** * Returns the raw JSON value of [spend]. * @@ -484,6 +783,24 @@ private constructor( */ @JsonProperty("tpm_limit") @ExcludeMissing fun _tpmLimit(): JsonField = tpmLimit + /** + * Returns the raw JSON value of [tpmLimitType]. + * + * Unlike [tpmLimitType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tpm_limit_type") + @ExcludeMissing + fun _tpmLimitType(): JsonField = tpmLimitType + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updated_at") + @ExcludeMissing + fun _updatedAt(): JsonField = updatedAt + /** * Returns the raw JSON value of [updatedBy]. * @@ -517,7 +834,6 @@ private constructor( * * The following fields are required: * ```java - * .expires() * .key() * ``` */ @@ -527,59 +843,77 @@ private constructor( /** A builder for [GenerateKeyResponse]. */ class Builder internal constructor() { - private var expires: JsonField? = null private var key: JsonField? = null private var token: JsonField = JsonMissing.of() - private var aliases: JsonValue = JsonMissing.of() + private var aliases: JsonField = JsonMissing.of() private var allowedCacheControls: JsonField>? = null + private var allowedPassthroughRoutes: JsonField>? = null + private var allowedRoutes: JsonField>? = null + private var allowedVectorStoreIndexes: JsonField>? = + null private var blocked: JsonField = JsonMissing.of() private var budgetDuration: JsonField = JsonMissing.of() private var budgetId: JsonField = JsonMissing.of() - private var config: JsonValue = JsonMissing.of() + private var config: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() private var createdBy: JsonField = JsonMissing.of() private var duration: JsonField = JsonMissing.of() private var enforcedParams: JsonField>? = null + private var expires: JsonField = JsonMissing.of() private var guardrails: JsonField>? = null private var keyAlias: JsonField = JsonMissing.of() private var keyName: JsonField = JsonMissing.of() - private var llmBudgetTable: JsonValue = JsonMissing.of() + private var litellmBudgetTable: JsonValue = JsonMissing.of() private var maxBudget: JsonField = JsonMissing.of() private var maxParallelRequests: JsonField = JsonMissing.of() - private var metadata: JsonValue = JsonMissing.of() - private var modelMaxBudget: JsonValue = JsonMissing.of() - private var modelRpmLimit: JsonValue = JsonMissing.of() - private var modelTpmLimit: JsonValue = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var modelMaxBudget: JsonField = JsonMissing.of() + private var modelRpmLimit: JsonField = JsonMissing.of() + private var modelTpmLimit: JsonField = JsonMissing.of() private var models: JsonField>? = null - private var permissions: JsonValue = JsonMissing.of() + private var objectPermission: JsonField = JsonMissing.of() + private var organizationId: JsonField = JsonMissing.of() + private var permissions: JsonField = JsonMissing.of() + private var prompts: JsonField>? = null + private var routerSettings: JsonField = JsonMissing.of() private var rpmLimit: JsonField = JsonMissing.of() + private var rpmLimitType: JsonField = JsonMissing.of() private var spend: JsonField = JsonMissing.of() private var tags: JsonField>? = null private var teamId: JsonField = JsonMissing.of() private var tokenId: JsonField = JsonMissing.of() private var tpmLimit: JsonField = JsonMissing.of() + private var tpmLimitType: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() private var updatedBy: JsonField = JsonMissing.of() private var userId: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(generateKeyResponse: GenerateKeyResponse) = apply { - expires = generateKeyResponse.expires key = generateKeyResponse.key token = generateKeyResponse.token aliases = generateKeyResponse.aliases allowedCacheControls = generateKeyResponse.allowedCacheControls.map { it.toMutableList() } + allowedPassthroughRoutes = + generateKeyResponse.allowedPassthroughRoutes.map { it.toMutableList() } + allowedRoutes = generateKeyResponse.allowedRoutes.map { it.toMutableList() } + allowedVectorStoreIndexes = + generateKeyResponse.allowedVectorStoreIndexes.map { it.toMutableList() } blocked = generateKeyResponse.blocked budgetDuration = generateKeyResponse.budgetDuration budgetId = generateKeyResponse.budgetId config = generateKeyResponse.config + createdAt = generateKeyResponse.createdAt createdBy = generateKeyResponse.createdBy duration = generateKeyResponse.duration enforcedParams = generateKeyResponse.enforcedParams.map { it.toMutableList() } + expires = generateKeyResponse.expires guardrails = generateKeyResponse.guardrails.map { it.toMutableList() } keyAlias = generateKeyResponse.keyAlias keyName = generateKeyResponse.keyName - llmBudgetTable = generateKeyResponse.llmBudgetTable + litellmBudgetTable = generateKeyResponse.litellmBudgetTable maxBudget = generateKeyResponse.maxBudget maxParallelRequests = generateKeyResponse.maxParallelRequests metadata = generateKeyResponse.metadata @@ -587,32 +921,25 @@ private constructor( modelRpmLimit = generateKeyResponse.modelRpmLimit modelTpmLimit = generateKeyResponse.modelTpmLimit models = generateKeyResponse.models.map { it.toMutableList() } + objectPermission = generateKeyResponse.objectPermission + organizationId = generateKeyResponse.organizationId permissions = generateKeyResponse.permissions + prompts = generateKeyResponse.prompts.map { it.toMutableList() } + routerSettings = generateKeyResponse.routerSettings rpmLimit = generateKeyResponse.rpmLimit + rpmLimitType = generateKeyResponse.rpmLimitType spend = generateKeyResponse.spend tags = generateKeyResponse.tags.map { it.toMutableList() } teamId = generateKeyResponse.teamId tokenId = generateKeyResponse.tokenId tpmLimit = generateKeyResponse.tpmLimit + tpmLimitType = generateKeyResponse.tpmLimitType + updatedAt = generateKeyResponse.updatedAt updatedBy = generateKeyResponse.updatedBy userId = generateKeyResponse.userId additionalProperties = generateKeyResponse.additionalProperties.toMutableMap() } - fun expires(expires: OffsetDateTime?) = expires(JsonField.ofNullable(expires)) - - /** Alias for calling [Builder.expires] with `expires.orElse(null)`. */ - fun expires(expires: Optional) = expires(expires.getOrNull()) - - /** - * Sets [Builder.expires] to an arbitrary JSON value. - * - * You should usually call [Builder.expires] with a well-typed [OffsetDateTime] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun expires(expires: JsonField) = apply { this.expires = expires } - fun key(key: String) = key(JsonField.of(key)) /** @@ -636,7 +963,18 @@ private constructor( */ fun token(token: JsonField) = apply { this.token = token } - fun aliases(aliases: JsonValue) = apply { this.aliases = aliases } + fun aliases(aliases: Aliases?) = aliases(JsonField.ofNullable(aliases)) + + /** Alias for calling [Builder.aliases] with `aliases.orElse(null)`. */ + fun aliases(aliases: Optional) = aliases(aliases.getOrNull()) + + /** + * Sets [Builder.aliases] to an arbitrary JSON value. + * + * You should usually call [Builder.aliases] with a well-typed [Aliases] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun aliases(aliases: JsonField) = apply { this.aliases = aliases } fun allowedCacheControls(allowedCacheControls: List?) = allowedCacheControls(JsonField.ofNullable(allowedCacheControls)) @@ -671,25 +1009,124 @@ private constructor( } } - fun blocked(blocked: Boolean?) = blocked(JsonField.ofNullable(blocked)) + fun allowedPassthroughRoutes(allowedPassthroughRoutes: List?) = + allowedPassthroughRoutes(JsonField.ofNullable(allowedPassthroughRoutes)) /** - * Alias for [Builder.blocked]. - * - * This unboxed primitive overload exists for backwards compatibility. + * Alias for calling [Builder.allowedPassthroughRoutes] with + * `allowedPassthroughRoutes.orElse(null)`. */ - fun blocked(blocked: Boolean) = blocked(blocked as Boolean?) + fun allowedPassthroughRoutes(allowedPassthroughRoutes: Optional>) = + allowedPassthroughRoutes(allowedPassthroughRoutes.getOrNull()) - /** Alias for calling [Builder.blocked] with `blocked.orElse(null)`. */ - fun blocked(blocked: Optional) = blocked(blocked.getOrNull()) + /** + * Sets [Builder.allowedPassthroughRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedPassthroughRoutes] with a well-typed + * `List` value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun allowedPassthroughRoutes(allowedPassthroughRoutes: JsonField>) = apply { + this.allowedPassthroughRoutes = allowedPassthroughRoutes.map { it.toMutableList() } + } /** - * Sets [Builder.blocked] to an arbitrary JSON value. + * Adds a single [JsonValue] to [allowedPassthroughRoutes]. * - * You should usually call [Builder.blocked] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws IllegalStateException if the field was previously set to a non-list. */ - fun blocked(blocked: JsonField) = apply { this.blocked = blocked } + fun addAllowedPassthroughRoute(allowedPassthroughRoute: JsonValue) = apply { + allowedPassthroughRoutes = + (allowedPassthroughRoutes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedPassthroughRoutes", it).add(allowedPassthroughRoute) + } + } + + fun allowedRoutes(allowedRoutes: List?) = + allowedRoutes(JsonField.ofNullable(allowedRoutes)) + + /** Alias for calling [Builder.allowedRoutes] with `allowedRoutes.orElse(null)`. */ + fun allowedRoutes(allowedRoutes: Optional>) = + allowedRoutes(allowedRoutes.getOrNull()) + + /** + * Sets [Builder.allowedRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedRoutes] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun allowedRoutes(allowedRoutes: JsonField>) = apply { + this.allowedRoutes = allowedRoutes.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [allowedRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedRoute(allowedRoute: JsonValue) = apply { + allowedRoutes = + (allowedRoutes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedRoutes", it).add(allowedRoute) + } + } + + fun allowedVectorStoreIndexes(allowedVectorStoreIndexes: List?) = + allowedVectorStoreIndexes(JsonField.ofNullable(allowedVectorStoreIndexes)) + + /** + * Alias for calling [Builder.allowedVectorStoreIndexes] with + * `allowedVectorStoreIndexes.orElse(null)`. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: Optional> + ) = allowedVectorStoreIndexes(allowedVectorStoreIndexes.getOrNull()) + + /** + * Sets [Builder.allowedVectorStoreIndexes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedVectorStoreIndexes] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: JsonField> + ) = apply { + this.allowedVectorStoreIndexes = allowedVectorStoreIndexes.map { it.toMutableList() } + } + + /** + * Adds a single [AllowedVectorStoreIndex] to [allowedVectorStoreIndexes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedVectorStoreIndex(allowedVectorStoreIndex: AllowedVectorStoreIndex) = apply { + allowedVectorStoreIndexes = + (allowedVectorStoreIndexes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedVectorStoreIndexes", it).add(allowedVectorStoreIndex) + } + } + + fun blocked(blocked: Boolean?) = blocked(JsonField.ofNullable(blocked)) + + /** + * Alias for [Builder.blocked]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun blocked(blocked: Boolean) = blocked(blocked as Boolean?) + + /** Alias for calling [Builder.blocked] with `blocked.orElse(null)`. */ + fun blocked(blocked: Optional) = blocked(blocked.getOrNull()) + + /** + * Sets [Builder.blocked] to an arbitrary JSON value. + * + * You should usually call [Builder.blocked] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun blocked(blocked: JsonField) = apply { this.blocked = blocked } fun budgetDuration(budgetDuration: String?) = budgetDuration(JsonField.ofNullable(budgetDuration)) @@ -722,7 +1159,32 @@ private constructor( */ fun budgetId(budgetId: JsonField) = apply { this.budgetId = budgetId } - fun config(config: JsonValue) = apply { this.config = config } + fun config(config: Config?) = config(JsonField.ofNullable(config)) + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [Config] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun config(config: JsonField) = apply { this.config = config } + + fun createdAt(createdAt: OffsetDateTime?) = createdAt(JsonField.ofNullable(createdAt)) + + /** Alias for calling [Builder.createdAt] with `createdAt.orElse(null)`. */ + fun createdAt(createdAt: Optional) = createdAt(createdAt.getOrNull()) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } fun createdBy(createdBy: String?) = createdBy(JsonField.ofNullable(createdBy)) @@ -781,6 +1243,20 @@ private constructor( } } + fun expires(expires: OffsetDateTime?) = expires(JsonField.ofNullable(expires)) + + /** Alias for calling [Builder.expires] with `expires.orElse(null)`. */ + fun expires(expires: Optional) = expires(expires.getOrNull()) + + /** + * Sets [Builder.expires] to an arbitrary JSON value. + * + * You should usually call [Builder.expires] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun expires(expires: JsonField) = apply { this.expires = expires } + fun guardrails(guardrails: List?) = guardrails(JsonField.ofNullable(guardrails)) /** Alias for calling [Builder.guardrails] with `guardrails.orElse(null)`. */ @@ -835,8 +1311,8 @@ private constructor( */ fun keyName(keyName: JsonField) = apply { this.keyName = keyName } - fun llmBudgetTable(llmBudgetTable: JsonValue) = apply { - this.llmBudgetTable = llmBudgetTable + fun litellmBudgetTable(litellmBudgetTable: JsonValue) = apply { + this.litellmBudgetTable = litellmBudgetTable } fun maxBudget(maxBudget: Double?) = maxBudget(JsonField.ofNullable(maxBudget)) @@ -888,15 +1364,73 @@ private constructor( this.maxParallelRequests = maxParallelRequests } - fun metadata(metadata: JsonValue) = apply { this.metadata = metadata } + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) - fun modelMaxBudget(modelMaxBudget: JsonValue) = apply { + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun modelMaxBudget(modelMaxBudget: ModelMaxBudget?) = + modelMaxBudget(JsonField.ofNullable(modelMaxBudget)) + + /** Alias for calling [Builder.modelMaxBudget] with `modelMaxBudget.orElse(null)`. */ + fun modelMaxBudget(modelMaxBudget: Optional) = + modelMaxBudget(modelMaxBudget.getOrNull()) + + /** + * Sets [Builder.modelMaxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.modelMaxBudget] with a well-typed [ModelMaxBudget] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelMaxBudget(modelMaxBudget: JsonField) = apply { this.modelMaxBudget = modelMaxBudget } - fun modelRpmLimit(modelRpmLimit: JsonValue) = apply { this.modelRpmLimit = modelRpmLimit } + fun modelRpmLimit(modelRpmLimit: ModelRpmLimit?) = + modelRpmLimit(JsonField.ofNullable(modelRpmLimit)) + + /** Alias for calling [Builder.modelRpmLimit] with `modelRpmLimit.orElse(null)`. */ + fun modelRpmLimit(modelRpmLimit: Optional) = + modelRpmLimit(modelRpmLimit.getOrNull()) + + /** + * Sets [Builder.modelRpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.modelRpmLimit] with a well-typed [ModelRpmLimit] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelRpmLimit(modelRpmLimit: JsonField) = apply { + this.modelRpmLimit = modelRpmLimit + } + + fun modelTpmLimit(modelTpmLimit: ModelTpmLimit?) = + modelTpmLimit(JsonField.ofNullable(modelTpmLimit)) + + /** Alias for calling [Builder.modelTpmLimit] with `modelTpmLimit.orElse(null)`. */ + fun modelTpmLimit(modelTpmLimit: Optional) = + modelTpmLimit(modelTpmLimit.getOrNull()) - fun modelTpmLimit(modelTpmLimit: JsonValue) = apply { this.modelTpmLimit = modelTpmLimit } + /** + * Sets [Builder.modelTpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.modelTpmLimit] with a well-typed [ModelTpmLimit] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelTpmLimit(modelTpmLimit: JsonField) = apply { + this.modelTpmLimit = modelTpmLimit + } fun models(models: List?) = models(JsonField.ofNullable(models)) @@ -926,7 +1460,104 @@ private constructor( } } - fun permissions(permissions: JsonValue) = apply { this.permissions = permissions } + fun objectPermission(objectPermission: ObjectPermission?) = + objectPermission(JsonField.ofNullable(objectPermission)) + + /** Alias for calling [Builder.objectPermission] with `objectPermission.orElse(null)`. */ + fun objectPermission(objectPermission: Optional) = + objectPermission(objectPermission.getOrNull()) + + /** + * Sets [Builder.objectPermission] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermission] with a well-typed [ObjectPermission] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun objectPermission(objectPermission: JsonField) = apply { + this.objectPermission = objectPermission + } + + fun organizationId(organizationId: String?) = + organizationId(JsonField.ofNullable(organizationId)) + + /** Alias for calling [Builder.organizationId] with `organizationId.orElse(null)`. */ + fun organizationId(organizationId: Optional) = + organizationId(organizationId.getOrNull()) + + /** + * Sets [Builder.organizationId] to an arbitrary JSON value. + * + * You should usually call [Builder.organizationId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun organizationId(organizationId: JsonField) = apply { + this.organizationId = organizationId + } + + fun permissions(permissions: Permissions?) = permissions(JsonField.ofNullable(permissions)) + + /** Alias for calling [Builder.permissions] with `permissions.orElse(null)`. */ + fun permissions(permissions: Optional) = permissions(permissions.getOrNull()) + + /** + * Sets [Builder.permissions] to an arbitrary JSON value. + * + * You should usually call [Builder.permissions] with a well-typed [Permissions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun permissions(permissions: JsonField) = apply { + this.permissions = permissions + } + + fun prompts(prompts: List?) = prompts(JsonField.ofNullable(prompts)) + + /** Alias for calling [Builder.prompts] with `prompts.orElse(null)`. */ + fun prompts(prompts: Optional>) = prompts(prompts.getOrNull()) + + /** + * Sets [Builder.prompts] to an arbitrary JSON value. + * + * You should usually call [Builder.prompts] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun prompts(prompts: JsonField>) = apply { + this.prompts = prompts.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [prompts]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addPrompt(prompt: String) = apply { + prompts = + (prompts ?: JsonField.of(mutableListOf())).also { + checkKnown("prompts", it).add(prompt) + } + } + + /** Set of params that you can modify via `router.update_settings()`. */ + fun routerSettings(routerSettings: RouterSettings?) = + routerSettings(JsonField.ofNullable(routerSettings)) + + /** Alias for calling [Builder.routerSettings] with `routerSettings.orElse(null)`. */ + fun routerSettings(routerSettings: Optional) = + routerSettings(routerSettings.getOrNull()) + + /** + * Sets [Builder.routerSettings] to an arbitrary JSON value. + * + * You should usually call [Builder.routerSettings] with a well-typed [RouterSettings] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun routerSettings(routerSettings: JsonField) = apply { + this.routerSettings = routerSettings + } fun rpmLimit(rpmLimit: Long?) = rpmLimit(JsonField.ofNullable(rpmLimit)) @@ -948,6 +1579,24 @@ private constructor( */ fun rpmLimit(rpmLimit: JsonField) = apply { this.rpmLimit = rpmLimit } + fun rpmLimitType(rpmLimitType: RpmLimitType?) = + rpmLimitType(JsonField.ofNullable(rpmLimitType)) + + /** Alias for calling [Builder.rpmLimitType] with `rpmLimitType.orElse(null)`. */ + fun rpmLimitType(rpmLimitType: Optional) = + rpmLimitType(rpmLimitType.getOrNull()) + + /** + * Sets [Builder.rpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.rpmLimitType] with a well-typed [RpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rpmLimitType(rpmLimitType: JsonField) = apply { + this.rpmLimitType = rpmLimitType + } + fun spend(spend: Double?) = spend(JsonField.ofNullable(spend)) /** @@ -1039,6 +1688,38 @@ private constructor( */ fun tpmLimit(tpmLimit: JsonField) = apply { this.tpmLimit = tpmLimit } + fun tpmLimitType(tpmLimitType: TpmLimitType?) = + tpmLimitType(JsonField.ofNullable(tpmLimitType)) + + /** Alias for calling [Builder.tpmLimitType] with `tpmLimitType.orElse(null)`. */ + fun tpmLimitType(tpmLimitType: Optional) = + tpmLimitType(tpmLimitType.getOrNull()) + + /** + * Sets [Builder.tpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.tpmLimitType] with a well-typed [TpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tpmLimitType(tpmLimitType: JsonField) = apply { + this.tpmLimitType = tpmLimitType + } + + fun updatedAt(updatedAt: OffsetDateTime?) = updatedAt(JsonField.ofNullable(updatedAt)) + + /** Alias for calling [Builder.updatedAt] with `updatedAt.orElse(null)`. */ + fun updatedAt(updatedAt: Optional) = updatedAt(updatedAt.getOrNull()) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun updatedAt(updatedAt: JsonField) = apply { this.updatedAt = updatedAt } + fun updatedBy(updatedBy: String?) = updatedBy(JsonField.ofNullable(updatedBy)) /** Alias for calling [Builder.updatedBy] with `updatedBy.orElse(null)`. */ @@ -1092,7 +1773,6 @@ private constructor( * * The following fields are required: * ```java - * .expires() * .key() * ``` * @@ -1100,22 +1780,26 @@ private constructor( */ fun build(): GenerateKeyResponse = GenerateKeyResponse( - checkRequired("expires", expires), checkRequired("key", key), token, aliases, (allowedCacheControls ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedPassthroughRoutes ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedRoutes ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedVectorStoreIndexes ?: JsonMissing.of()).map { it.toImmutable() }, blocked, budgetDuration, budgetId, config, + createdAt, createdBy, duration, (enforcedParams ?: JsonMissing.of()).map { it.toImmutable() }, + expires, (guardrails ?: JsonMissing.of()).map { it.toImmutable() }, keyAlias, keyName, - llmBudgetTable, + litellmBudgetTable, maxBudget, maxParallelRequests, metadata, @@ -1123,13 +1807,20 @@ private constructor( modelRpmLimit, modelTpmLimit, (models ?: JsonMissing.of()).map { it.toImmutable() }, + objectPermission, + organizationId, permissions, + (prompts ?: JsonMissing.of()).map { it.toImmutable() }, + routerSettings, rpmLimit, + rpmLimitType, spend, (tags ?: JsonMissing.of()).map { it.toImmutable() }, teamId, tokenId, tpmLimit, + tpmLimitType, + updatedAt, updatedBy, userId, additionalProperties.toMutableMap(), @@ -1143,47 +1834,3336 @@ private constructor( return@apply } - expires() key() token() + aliases().ifPresent { it.validate() } allowedCacheControls() + allowedPassthroughRoutes() + allowedRoutes() + allowedVectorStoreIndexes().ifPresent { it.forEach { it.validate() } } blocked() budgetDuration() budgetId() + config().ifPresent { it.validate() } + createdAt() createdBy() duration() enforcedParams() + expires() guardrails() keyAlias() keyName() maxBudget() maxParallelRequests() + metadata().ifPresent { it.validate() } + modelMaxBudget().ifPresent { it.validate() } + modelRpmLimit().ifPresent { it.validate() } + modelTpmLimit().ifPresent { it.validate() } models() + objectPermission().ifPresent { it.validate() } + organizationId() + permissions().ifPresent { it.validate() } + prompts() + routerSettings().ifPresent { it.validate() } rpmLimit() + rpmLimitType().ifPresent { it.validate() } spend() tags() teamId() tokenId() tpmLimit() + tpmLimitType().ifPresent { it.validate() } + updatedAt() updatedBy() userId() validated = true } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (key.asKnown().isPresent) 1 else 0) + + (if (token.asKnown().isPresent) 1 else 0) + + (aliases.asKnown().getOrNull()?.validity() ?: 0) + + (allowedCacheControls.asKnown().getOrNull()?.size ?: 0) + + (allowedPassthroughRoutes.asKnown().getOrNull()?.size ?: 0) + + (allowedRoutes.asKnown().getOrNull()?.size ?: 0) + + (allowedVectorStoreIndexes.asKnown().getOrNull()?.sumOf { it.validity().toInt() } + ?: 0) + + (if (blocked.asKnown().isPresent) 1 else 0) + + (if (budgetDuration.asKnown().isPresent) 1 else 0) + + (if (budgetId.asKnown().isPresent) 1 else 0) + + (config.asKnown().getOrNull()?.validity() ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (createdBy.asKnown().isPresent) 1 else 0) + + (if (duration.asKnown().isPresent) 1 else 0) + + (enforcedParams.asKnown().getOrNull()?.size ?: 0) + + (if (expires.asKnown().isPresent) 1 else 0) + + (guardrails.asKnown().getOrNull()?.size ?: 0) + + (if (keyAlias.asKnown().isPresent) 1 else 0) + + (if (keyName.asKnown().isPresent) 1 else 0) + + (if (maxBudget.asKnown().isPresent) 1 else 0) + + (if (maxParallelRequests.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (modelMaxBudget.asKnown().getOrNull()?.validity() ?: 0) + + (modelRpmLimit.asKnown().getOrNull()?.validity() ?: 0) + + (modelTpmLimit.asKnown().getOrNull()?.validity() ?: 0) + + (models.asKnown().getOrNull()?.size ?: 0) + + (objectPermission.asKnown().getOrNull()?.validity() ?: 0) + + (if (organizationId.asKnown().isPresent) 1 else 0) + + (permissions.asKnown().getOrNull()?.validity() ?: 0) + + (prompts.asKnown().getOrNull()?.size ?: 0) + + (routerSettings.asKnown().getOrNull()?.validity() ?: 0) + + (if (rpmLimit.asKnown().isPresent) 1 else 0) + + (rpmLimitType.asKnown().getOrNull()?.validity() ?: 0) + + (if (spend.asKnown().isPresent) 1 else 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + (if (teamId.asKnown().isPresent) 1 else 0) + + (if (tokenId.asKnown().isPresent) 1 else 0) + + (if (tpmLimit.asKnown().isPresent) 1 else 0) + + (tpmLimitType.asKnown().getOrNull()?.validity() ?: 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + (if (updatedBy.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + class Aliases + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Aliases]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Aliases]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aliases: Aliases) = apply { + additionalProperties = aliases.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Aliases]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Aliases = Aliases(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Aliases = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Aliases && additionalProperties == other.additionalProperties } - return /* spotless:off */ other is GenerateKeyResponse && expires == other.expires && key == other.key && token == other.token && aliases == other.aliases && allowedCacheControls == other.allowedCacheControls && blocked == other.blocked && budgetDuration == other.budgetDuration && budgetId == other.budgetId && config == other.config && createdBy == other.createdBy && duration == other.duration && enforcedParams == other.enforcedParams && guardrails == other.guardrails && keyAlias == other.keyAlias && keyName == other.keyName && llmBudgetTable == other.llmBudgetTable && maxBudget == other.maxBudget && maxParallelRequests == other.maxParallelRequests && metadata == other.metadata && modelMaxBudget == other.modelMaxBudget && modelRpmLimit == other.modelRpmLimit && modelTpmLimit == other.modelTpmLimit && models == other.models && permissions == other.permissions && rpmLimit == other.rpmLimit && spend == other.spend && tags == other.tags && teamId == other.teamId && tokenId == other.tokenId && tpmLimit == other.tpmLimit && updatedBy == other.updatedBy && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Aliases{additionalProperties=$additionalProperties}" } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(expires, key, token, aliases, allowedCacheControls, blocked, budgetDuration, budgetId, config, createdBy, duration, enforcedParams, guardrails, keyAlias, keyName, llmBudgetTable, maxBudget, maxParallelRequests, metadata, modelMaxBudget, modelRpmLimit, modelTpmLimit, models, permissions, rpmLimit, spend, tags, teamId, tokenId, tpmLimit, updatedBy, userId, additionalProperties) } - /* spotless:on */ + class AllowedVectorStoreIndex + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val indexName: JsonField, + private val indexPermissions: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("index_name") + @ExcludeMissing + indexName: JsonField = JsonMissing.of(), + @JsonProperty("index_permissions") + @ExcludeMissing + indexPermissions: JsonField> = JsonMissing.of(), + ) : this(indexName, indexPermissions, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun indexName(): String = indexName.getRequired("index_name") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun indexPermissions(): List = + indexPermissions.getRequired("index_permissions") + + /** + * Returns the raw JSON value of [indexName]. + * + * Unlike [indexName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("index_name") @ExcludeMissing fun _indexName(): JsonField = indexName + + /** + * Returns the raw JSON value of [indexPermissions]. + * + * Unlike [indexPermissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("index_permissions") + @ExcludeMissing + fun _indexPermissions(): JsonField> = indexPermissions + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AllowedVectorStoreIndex]. + * + * The following fields are required: + * ```java + * .indexName() + * .indexPermissions() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AllowedVectorStoreIndex]. */ + class Builder internal constructor() { + + private var indexName: JsonField? = null + private var indexPermissions: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(allowedVectorStoreIndex: AllowedVectorStoreIndex) = apply { + indexName = allowedVectorStoreIndex.indexName + indexPermissions = + allowedVectorStoreIndex.indexPermissions.map { it.toMutableList() } + additionalProperties = allowedVectorStoreIndex.additionalProperties.toMutableMap() + } + + fun indexName(indexName: String) = indexName(JsonField.of(indexName)) + + /** + * Sets [Builder.indexName] to an arbitrary JSON value. + * + * You should usually call [Builder.indexName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun indexName(indexName: JsonField) = apply { this.indexName = indexName } + + fun indexPermissions(indexPermissions: List) = + indexPermissions(JsonField.of(indexPermissions)) + + /** + * Sets [Builder.indexPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.indexPermissions] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun indexPermissions(indexPermissions: JsonField>) = apply { + this.indexPermissions = indexPermissions.map { it.toMutableList() } + } + + /** + * Adds a single [IndexPermission] to [indexPermissions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addIndexPermission(indexPermission: IndexPermission) = apply { + indexPermissions = + (indexPermissions ?: JsonField.of(mutableListOf())).also { + checkKnown("indexPermissions", it).add(indexPermission) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AllowedVectorStoreIndex]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .indexName() + * .indexPermissions() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AllowedVectorStoreIndex = + AllowedVectorStoreIndex( + checkRequired("indexName", indexName), + checkRequired("indexPermissions", indexPermissions).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AllowedVectorStoreIndex = apply { + if (validated) { + return@apply + } + + indexName() + indexPermissions().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (indexName.asKnown().isPresent) 1 else 0) + + (indexPermissions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + class IndexPermission + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val READ = of("read") + + @JvmField val WRITE = of("write") + + @JvmStatic fun of(value: String) = IndexPermission(JsonField.of(value)) + } + + /** An enum containing [IndexPermission]'s known values. */ + enum class Known { + READ, + WRITE, + } + + /** + * An enum containing [IndexPermission]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [IndexPermission] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + READ, + WRITE, + /** + * An enum member indicating that [IndexPermission] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + READ -> Value.READ + WRITE -> Value.WRITE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + READ -> Known.READ + WRITE -> Known.WRITE + else -> throw HanzoInvalidDataException("Unknown IndexPermission: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + HanzoInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): IndexPermission = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is IndexPermission && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AllowedVectorStoreIndex && + indexName == other.indexName && + indexPermissions == other.indexPermissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(indexName, indexPermissions, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AllowedVectorStoreIndex{indexName=$indexName, indexPermissions=$indexPermissions, additionalProperties=$additionalProperties}" + } + + class Config + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Config]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Config]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(config: Config) = apply { + additionalProperties = config.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Config]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Config = Config(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Config = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Config && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Config{additionalProperties=$additionalProperties}" + } + + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + class ModelMaxBudget + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelMaxBudget]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelMaxBudget]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelMaxBudget: ModelMaxBudget) = apply { + additionalProperties = modelMaxBudget.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelMaxBudget]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelMaxBudget = ModelMaxBudget(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelMaxBudget = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelMaxBudget && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelMaxBudget{additionalProperties=$additionalProperties}" + } + + class ModelRpmLimit + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelRpmLimit]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelRpmLimit]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelRpmLimit: ModelRpmLimit) = apply { + additionalProperties = modelRpmLimit.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelRpmLimit]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelRpmLimit = ModelRpmLimit(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelRpmLimit = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelRpmLimit && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelRpmLimit{additionalProperties=$additionalProperties}" + } + + class ModelTpmLimit + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelTpmLimit]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelTpmLimit]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelTpmLimit: ModelTpmLimit) = apply { + additionalProperties = modelTpmLimit.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelTpmLimit]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelTpmLimit = ModelTpmLimit(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelTpmLimit = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelTpmLimit && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelTpmLimit{additionalProperties=$additionalProperties}" + } + + class ObjectPermission + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val agentAccessGroups: JsonField>, + private val agents: JsonField>, + private val mcpAccessGroups: JsonField>, + private val mcpServers: JsonField>, + private val mcpToolPermissions: JsonField, + private val vectorStores: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("agent_access_groups") + @ExcludeMissing + agentAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("agents") + @ExcludeMissing + agents: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_access_groups") + @ExcludeMissing + mcpAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_servers") + @ExcludeMissing + mcpServers: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + mcpToolPermissions: JsonField = JsonMissing.of(), + @JsonProperty("vector_stores") + @ExcludeMissing + vectorStores: JsonField> = JsonMissing.of(), + ) : this( + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun agentAccessGroups(): Optional> = + agentAccessGroups.getOptional("agent_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun agents(): Optional> = agents.getOptional("agents") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpAccessGroups(): Optional> = + mcpAccessGroups.getOptional("mcp_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpServers(): Optional> = mcpServers.getOptional("mcp_servers") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpToolPermissions(): Optional = + mcpToolPermissions.getOptional("mcp_tool_permissions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun vectorStores(): Optional> = vectorStores.getOptional("vector_stores") + + /** + * Returns the raw JSON value of [agentAccessGroups]. + * + * Unlike [agentAccessGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("agent_access_groups") + @ExcludeMissing + fun _agentAccessGroups(): JsonField> = agentAccessGroups + + /** + * Returns the raw JSON value of [agents]. + * + * Unlike [agents], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("agents") @ExcludeMissing fun _agents(): JsonField> = agents + + /** + * Returns the raw JSON value of [mcpAccessGroups]. + * + * Unlike [mcpAccessGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("mcp_access_groups") + @ExcludeMissing + fun _mcpAccessGroups(): JsonField> = mcpAccessGroups + + /** + * Returns the raw JSON value of [mcpServers]. + * + * Unlike [mcpServers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("mcp_servers") + @ExcludeMissing + fun _mcpServers(): JsonField> = mcpServers + + /** + * Returns the raw JSON value of [mcpToolPermissions]. + * + * Unlike [mcpToolPermissions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + fun _mcpToolPermissions(): JsonField = mcpToolPermissions + + /** + * Returns the raw JSON value of [vectorStores]. + * + * Unlike [vectorStores], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("vector_stores") + @ExcludeMissing + fun _vectorStores(): JsonField> = vectorStores + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ObjectPermission]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ObjectPermission]. */ + class Builder internal constructor() { + + private var agentAccessGroups: JsonField>? = null + private var agents: JsonField>? = null + private var mcpAccessGroups: JsonField>? = null + private var mcpServers: JsonField>? = null + private var mcpToolPermissions: JsonField = JsonMissing.of() + private var vectorStores: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(objectPermission: ObjectPermission) = apply { + agentAccessGroups = objectPermission.agentAccessGroups.map { it.toMutableList() } + agents = objectPermission.agents.map { it.toMutableList() } + mcpAccessGroups = objectPermission.mcpAccessGroups.map { it.toMutableList() } + mcpServers = objectPermission.mcpServers.map { it.toMutableList() } + mcpToolPermissions = objectPermission.mcpToolPermissions + vectorStores = objectPermission.vectorStores.map { it.toMutableList() } + additionalProperties = objectPermission.additionalProperties.toMutableMap() + } + + fun agentAccessGroups(agentAccessGroups: List?) = + agentAccessGroups(JsonField.ofNullable(agentAccessGroups)) + + /** + * Alias for calling [Builder.agentAccessGroups] with `agentAccessGroups.orElse(null)`. + */ + fun agentAccessGroups(agentAccessGroups: Optional>) = + agentAccessGroups(agentAccessGroups.getOrNull()) + + /** + * Sets [Builder.agentAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.agentAccessGroups] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun agentAccessGroups(agentAccessGroups: JsonField>) = apply { + this.agentAccessGroups = agentAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agentAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgentAccessGroup(agentAccessGroup: String) = apply { + agentAccessGroups = + (agentAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("agentAccessGroups", it).add(agentAccessGroup) + } + } + + fun agents(agents: List?) = agents(JsonField.ofNullable(agents)) + + /** Alias for calling [Builder.agents] with `agents.orElse(null)`. */ + fun agents(agents: Optional>) = agents(agents.getOrNull()) + + /** + * Sets [Builder.agents] to an arbitrary JSON value. + * + * You should usually call [Builder.agents] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun agents(agents: JsonField>) = apply { + this.agents = agents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgent(agent: String) = apply { + agents = + (agents ?: JsonField.of(mutableListOf())).also { + checkKnown("agents", it).add(agent) + } + } + + fun mcpAccessGroups(mcpAccessGroups: List?) = + mcpAccessGroups(JsonField.ofNullable(mcpAccessGroups)) + + /** Alias for calling [Builder.mcpAccessGroups] with `mcpAccessGroups.orElse(null)`. */ + fun mcpAccessGroups(mcpAccessGroups: Optional>) = + mcpAccessGroups(mcpAccessGroups.getOrNull()) + + /** + * Sets [Builder.mcpAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpAccessGroups] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun mcpAccessGroups(mcpAccessGroups: JsonField>) = apply { + this.mcpAccessGroups = mcpAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpAccessGroup(mcpAccessGroup: String) = apply { + mcpAccessGroups = + (mcpAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpAccessGroups", it).add(mcpAccessGroup) + } + } + + fun mcpServers(mcpServers: List?) = mcpServers(JsonField.ofNullable(mcpServers)) + + /** Alias for calling [Builder.mcpServers] with `mcpServers.orElse(null)`. */ + fun mcpServers(mcpServers: Optional>) = mcpServers(mcpServers.getOrNull()) + + /** + * Sets [Builder.mcpServers] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpServers] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun mcpServers(mcpServers: JsonField>) = apply { + this.mcpServers = mcpServers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpServers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpServer(mcpServer: String) = apply { + mcpServers = + (mcpServers ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpServers", it).add(mcpServer) + } + } + + fun mcpToolPermissions(mcpToolPermissions: McpToolPermissions?) = + mcpToolPermissions(JsonField.ofNullable(mcpToolPermissions)) + + /** + * Alias for calling [Builder.mcpToolPermissions] with + * `mcpToolPermissions.orElse(null)`. + */ + fun mcpToolPermissions(mcpToolPermissions: Optional) = + mcpToolPermissions(mcpToolPermissions.getOrNull()) + + /** + * Sets [Builder.mcpToolPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpToolPermissions] with a well-typed + * [McpToolPermissions] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun mcpToolPermissions(mcpToolPermissions: JsonField) = apply { + this.mcpToolPermissions = mcpToolPermissions + } + + fun vectorStores(vectorStores: List?) = + vectorStores(JsonField.ofNullable(vectorStores)) + + /** Alias for calling [Builder.vectorStores] with `vectorStores.orElse(null)`. */ + fun vectorStores(vectorStores: Optional>) = + vectorStores(vectorStores.getOrNull()) + + /** + * Sets [Builder.vectorStores] to an arbitrary JSON value. + * + * You should usually call [Builder.vectorStores] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun vectorStores(vectorStores: JsonField>) = apply { + this.vectorStores = vectorStores.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [vectorStores]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addVectorStore(vectorStore: String) = apply { + vectorStores = + (vectorStores ?: JsonField.of(mutableListOf())).also { + checkKnown("vectorStores", it).add(vectorStore) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ObjectPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ObjectPermission = + ObjectPermission( + (agentAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (agents ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpServers ?: JsonMissing.of()).map { it.toImmutable() }, + mcpToolPermissions, + (vectorStores ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ObjectPermission = apply { + if (validated) { + return@apply + } + + agentAccessGroups() + agents() + mcpAccessGroups() + mcpServers() + mcpToolPermissions().ifPresent { it.validate() } + vectorStores() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (agentAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (agents.asKnown().getOrNull()?.size ?: 0) + + (mcpAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (mcpServers.asKnown().getOrNull()?.size ?: 0) + + (mcpToolPermissions.asKnown().getOrNull()?.validity() ?: 0) + + (vectorStores.asKnown().getOrNull()?.size ?: 0) + + class McpToolPermissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [McpToolPermissions]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [McpToolPermissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(mcpToolPermissions: McpToolPermissions) = apply { + additionalProperties = mcpToolPermissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [McpToolPermissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): McpToolPermissions = + McpToolPermissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): McpToolPermissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is McpToolPermissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "McpToolPermissions{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ObjectPermission && + agentAccessGroups == other.agentAccessGroups && + agents == other.agents && + mcpAccessGroups == other.mcpAccessGroups && + mcpServers == other.mcpServers && + mcpToolPermissions == other.mcpToolPermissions && + vectorStores == other.vectorStores && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ObjectPermission{agentAccessGroups=$agentAccessGroups, agents=$agents, mcpAccessGroups=$mcpAccessGroups, mcpServers=$mcpServers, mcpToolPermissions=$mcpToolPermissions, vectorStores=$vectorStores, additionalProperties=$additionalProperties}" + } + + class Permissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Permissions]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Permissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(permissions: Permissions) = apply { + additionalProperties = permissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Permissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Permissions = Permissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Permissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Permissions && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Permissions{additionalProperties=$additionalProperties}" + } + + /** Set of params that you can modify via `router.update_settings()`. */ + class RouterSettings + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val allowedFails: JsonField, + private val contextWindowFallbacks: JsonField>, + private val cooldownTime: JsonField, + private val fallbacks: JsonField>, + private val maxRetries: JsonField, + private val modelGroupAlias: JsonField, + private val modelGroupRetryPolicy: JsonField, + private val numRetries: JsonField, + private val retryAfter: JsonField, + private val routingStrategy: JsonField, + private val routingStrategyArgs: JsonField, + private val timeout: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("allowed_fails") + @ExcludeMissing + allowedFails: JsonField = JsonMissing.of(), + @JsonProperty("context_window_fallbacks") + @ExcludeMissing + contextWindowFallbacks: JsonField> = JsonMissing.of(), + @JsonProperty("cooldown_time") + @ExcludeMissing + cooldownTime: JsonField = JsonMissing.of(), + @JsonProperty("fallbacks") + @ExcludeMissing + fallbacks: JsonField> = JsonMissing.of(), + @JsonProperty("max_retries") + @ExcludeMissing + maxRetries: JsonField = JsonMissing.of(), + @JsonProperty("model_group_alias") + @ExcludeMissing + modelGroupAlias: JsonField = JsonMissing.of(), + @JsonProperty("model_group_retry_policy") + @ExcludeMissing + modelGroupRetryPolicy: JsonField = JsonMissing.of(), + @JsonProperty("num_retries") + @ExcludeMissing + numRetries: JsonField = JsonMissing.of(), + @JsonProperty("retry_after") + @ExcludeMissing + retryAfter: JsonField = JsonMissing.of(), + @JsonProperty("routing_strategy") + @ExcludeMissing + routingStrategy: JsonField = JsonMissing.of(), + @JsonProperty("routing_strategy_args") + @ExcludeMissing + routingStrategyArgs: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + ) : this( + allowedFails, + contextWindowFallbacks, + cooldownTime, + fallbacks, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedFails(): Optional = allowedFails.getOptional("allowed_fails") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun contextWindowFallbacks(): Optional> = + contextWindowFallbacks.getOptional("context_window_fallbacks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cooldownTime(): Optional = cooldownTime.getOptional("cooldown_time") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fallbacks(): Optional> = fallbacks.getOptional("fallbacks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxRetries(): Optional = maxRetries.getOptional("max_retries") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelGroupAlias(): Optional = + modelGroupAlias.getOptional("model_group_alias") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelGroupRetryPolicy(): Optional = + modelGroupRetryPolicy.getOptional("model_group_retry_policy") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun numRetries(): Optional = numRetries.getOptional("num_retries") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun retryAfter(): Optional = retryAfter.getOptional("retry_after") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routingStrategy(): Optional = routingStrategy.getOptional("routing_strategy") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routingStrategyArgs(): Optional = + routingStrategyArgs.getOptional("routing_strategy_args") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = timeout.getOptional("timeout") + + /** + * Returns the raw JSON value of [allowedFails]. + * + * Unlike [allowedFails], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("allowed_fails") + @ExcludeMissing + fun _allowedFails(): JsonField = allowedFails + + /** + * Returns the raw JSON value of [contextWindowFallbacks]. + * + * Unlike [contextWindowFallbacks], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("context_window_fallbacks") + @ExcludeMissing + fun _contextWindowFallbacks(): JsonField> = + contextWindowFallbacks + + /** + * Returns the raw JSON value of [cooldownTime]. + * + * Unlike [cooldownTime], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cooldown_time") + @ExcludeMissing + fun _cooldownTime(): JsonField = cooldownTime + + /** + * Returns the raw JSON value of [fallbacks]. + * + * Unlike [fallbacks], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fallbacks") + @ExcludeMissing + fun _fallbacks(): JsonField> = fallbacks + + /** + * Returns the raw JSON value of [maxRetries]. + * + * Unlike [maxRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("max_retries") @ExcludeMissing fun _maxRetries(): JsonField = maxRetries + + /** + * Returns the raw JSON value of [modelGroupAlias]. + * + * Unlike [modelGroupAlias], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("model_group_alias") + @ExcludeMissing + fun _modelGroupAlias(): JsonField = modelGroupAlias + + /** + * Returns the raw JSON value of [modelGroupRetryPolicy]. + * + * Unlike [modelGroupRetryPolicy], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("model_group_retry_policy") + @ExcludeMissing + fun _modelGroupRetryPolicy(): JsonField = modelGroupRetryPolicy + + /** + * Returns the raw JSON value of [numRetries]. + * + * Unlike [numRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("num_retries") @ExcludeMissing fun _numRetries(): JsonField = numRetries + + /** + * Returns the raw JSON value of [retryAfter]. + * + * Unlike [retryAfter], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("retry_after") + @ExcludeMissing + fun _retryAfter(): JsonField = retryAfter + + /** + * Returns the raw JSON value of [routingStrategy]. + * + * Unlike [routingStrategy], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("routing_strategy") + @ExcludeMissing + fun _routingStrategy(): JsonField = routingStrategy + + /** + * Returns the raw JSON value of [routingStrategyArgs]. + * + * Unlike [routingStrategyArgs], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("routing_strategy_args") + @ExcludeMissing + fun _routingStrategyArgs(): JsonField = routingStrategyArgs + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RouterSettings]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RouterSettings]. */ + class Builder internal constructor() { + + private var allowedFails: JsonField = JsonMissing.of() + private var contextWindowFallbacks: JsonField>? = + null + private var cooldownTime: JsonField = JsonMissing.of() + private var fallbacks: JsonField>? = null + private var maxRetries: JsonField = JsonMissing.of() + private var modelGroupAlias: JsonField = JsonMissing.of() + private var modelGroupRetryPolicy: JsonField = JsonMissing.of() + private var numRetries: JsonField = JsonMissing.of() + private var retryAfter: JsonField = JsonMissing.of() + private var routingStrategy: JsonField = JsonMissing.of() + private var routingStrategyArgs: JsonField = JsonMissing.of() + private var timeout: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(routerSettings: RouterSettings) = apply { + allowedFails = routerSettings.allowedFails + contextWindowFallbacks = + routerSettings.contextWindowFallbacks.map { it.toMutableList() } + cooldownTime = routerSettings.cooldownTime + fallbacks = routerSettings.fallbacks.map { it.toMutableList() } + maxRetries = routerSettings.maxRetries + modelGroupAlias = routerSettings.modelGroupAlias + modelGroupRetryPolicy = routerSettings.modelGroupRetryPolicy + numRetries = routerSettings.numRetries + retryAfter = routerSettings.retryAfter + routingStrategy = routerSettings.routingStrategy + routingStrategyArgs = routerSettings.routingStrategyArgs + timeout = routerSettings.timeout + additionalProperties = routerSettings.additionalProperties.toMutableMap() + } + + fun allowedFails(allowedFails: Long?) = allowedFails(JsonField.ofNullable(allowedFails)) + + /** + * Alias for [Builder.allowedFails]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun allowedFails(allowedFails: Long) = allowedFails(allowedFails as Long?) + + /** Alias for calling [Builder.allowedFails] with `allowedFails.orElse(null)`. */ + fun allowedFails(allowedFails: Optional) = allowedFails(allowedFails.getOrNull()) + + /** + * Sets [Builder.allowedFails] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedFails] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun allowedFails(allowedFails: JsonField) = apply { + this.allowedFails = allowedFails + } + + fun contextWindowFallbacks(contextWindowFallbacks: List?) = + contextWindowFallbacks(JsonField.ofNullable(contextWindowFallbacks)) + + /** + * Alias for calling [Builder.contextWindowFallbacks] with + * `contextWindowFallbacks.orElse(null)`. + */ + fun contextWindowFallbacks( + contextWindowFallbacks: Optional> + ) = contextWindowFallbacks(contextWindowFallbacks.getOrNull()) + + /** + * Sets [Builder.contextWindowFallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.contextWindowFallbacks] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun contextWindowFallbacks( + contextWindowFallbacks: JsonField> + ) = apply { + this.contextWindowFallbacks = contextWindowFallbacks.map { it.toMutableList() } + } + + /** + * Adds a single [ContextWindowFallback] to [contextWindowFallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addContextWindowFallback(contextWindowFallback: ContextWindowFallback) = apply { + contextWindowFallbacks = + (contextWindowFallbacks ?: JsonField.of(mutableListOf())).also { + checkKnown("contextWindowFallbacks", it).add(contextWindowFallback) + } + } + + fun cooldownTime(cooldownTime: Double?) = + cooldownTime(JsonField.ofNullable(cooldownTime)) + + /** + * Alias for [Builder.cooldownTime]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cooldownTime(cooldownTime: Double) = cooldownTime(cooldownTime as Double?) + + /** Alias for calling [Builder.cooldownTime] with `cooldownTime.orElse(null)`. */ + fun cooldownTime(cooldownTime: Optional) = + cooldownTime(cooldownTime.getOrNull()) + + /** + * Sets [Builder.cooldownTime] to an arbitrary JSON value. + * + * You should usually call [Builder.cooldownTime] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun cooldownTime(cooldownTime: JsonField) = apply { + this.cooldownTime = cooldownTime + } + + fun fallbacks(fallbacks: List?) = fallbacks(JsonField.ofNullable(fallbacks)) + + /** Alias for calling [Builder.fallbacks] with `fallbacks.orElse(null)`. */ + fun fallbacks(fallbacks: Optional>) = fallbacks(fallbacks.getOrNull()) + + /** + * Sets [Builder.fallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.fallbacks] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fallbacks(fallbacks: JsonField>) = apply { + this.fallbacks = fallbacks.map { it.toMutableList() } + } + + /** + * Adds a single [Fallback] to [fallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFallback(fallback: Fallback) = apply { + fallbacks = + (fallbacks ?: JsonField.of(mutableListOf())).also { + checkKnown("fallbacks", it).add(fallback) + } + } + + fun maxRetries(maxRetries: Long?) = maxRetries(JsonField.ofNullable(maxRetries)) + + /** + * Alias for [Builder.maxRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxRetries(maxRetries: Long) = maxRetries(maxRetries as Long?) + + /** Alias for calling [Builder.maxRetries] with `maxRetries.orElse(null)`. */ + fun maxRetries(maxRetries: Optional) = maxRetries(maxRetries.getOrNull()) + + /** + * Sets [Builder.maxRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.maxRetries] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxRetries(maxRetries: JsonField) = apply { this.maxRetries = maxRetries } + + fun modelGroupAlias(modelGroupAlias: ModelGroupAlias?) = + modelGroupAlias(JsonField.ofNullable(modelGroupAlias)) + + /** Alias for calling [Builder.modelGroupAlias] with `modelGroupAlias.orElse(null)`. */ + fun modelGroupAlias(modelGroupAlias: Optional) = + modelGroupAlias(modelGroupAlias.getOrNull()) + + /** + * Sets [Builder.modelGroupAlias] to an arbitrary JSON value. + * + * You should usually call [Builder.modelGroupAlias] with a well-typed [ModelGroupAlias] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun modelGroupAlias(modelGroupAlias: JsonField) = apply { + this.modelGroupAlias = modelGroupAlias + } + + fun modelGroupRetryPolicy(modelGroupRetryPolicy: ModelGroupRetryPolicy?) = + modelGroupRetryPolicy(JsonField.ofNullable(modelGroupRetryPolicy)) + + /** + * Alias for calling [Builder.modelGroupRetryPolicy] with + * `modelGroupRetryPolicy.orElse(null)`. + */ + fun modelGroupRetryPolicy(modelGroupRetryPolicy: Optional) = + modelGroupRetryPolicy(modelGroupRetryPolicy.getOrNull()) + + /** + * Sets [Builder.modelGroupRetryPolicy] to an arbitrary JSON value. + * + * You should usually call [Builder.modelGroupRetryPolicy] with a well-typed + * [ModelGroupRetryPolicy] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun modelGroupRetryPolicy(modelGroupRetryPolicy: JsonField) = + apply { + this.modelGroupRetryPolicy = modelGroupRetryPolicy + } + + fun numRetries(numRetries: Long?) = numRetries(JsonField.ofNullable(numRetries)) + + /** + * Alias for [Builder.numRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun numRetries(numRetries: Long) = numRetries(numRetries as Long?) + + /** Alias for calling [Builder.numRetries] with `numRetries.orElse(null)`. */ + fun numRetries(numRetries: Optional) = numRetries(numRetries.getOrNull()) + + /** + * Sets [Builder.numRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.numRetries] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun numRetries(numRetries: JsonField) = apply { this.numRetries = numRetries } + + fun retryAfter(retryAfter: Double?) = retryAfter(JsonField.ofNullable(retryAfter)) + + /** + * Alias for [Builder.retryAfter]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun retryAfter(retryAfter: Double) = retryAfter(retryAfter as Double?) + + /** Alias for calling [Builder.retryAfter] with `retryAfter.orElse(null)`. */ + fun retryAfter(retryAfter: Optional) = retryAfter(retryAfter.getOrNull()) + + /** + * Sets [Builder.retryAfter] to an arbitrary JSON value. + * + * You should usually call [Builder.retryAfter] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun retryAfter(retryAfter: JsonField) = apply { this.retryAfter = retryAfter } + + fun routingStrategy(routingStrategy: String?) = + routingStrategy(JsonField.ofNullable(routingStrategy)) + + /** Alias for calling [Builder.routingStrategy] with `routingStrategy.orElse(null)`. */ + fun routingStrategy(routingStrategy: Optional) = + routingStrategy(routingStrategy.getOrNull()) + + /** + * Sets [Builder.routingStrategy] to an arbitrary JSON value. + * + * You should usually call [Builder.routingStrategy] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun routingStrategy(routingStrategy: JsonField) = apply { + this.routingStrategy = routingStrategy + } + + fun routingStrategyArgs(routingStrategyArgs: RoutingStrategyArgs?) = + routingStrategyArgs(JsonField.ofNullable(routingStrategyArgs)) + + /** + * Alias for calling [Builder.routingStrategyArgs] with + * `routingStrategyArgs.orElse(null)`. + */ + fun routingStrategyArgs(routingStrategyArgs: Optional) = + routingStrategyArgs(routingStrategyArgs.getOrNull()) + + /** + * Sets [Builder.routingStrategyArgs] to an arbitrary JSON value. + * + * You should usually call [Builder.routingStrategyArgs] with a well-typed + * [RoutingStrategyArgs] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun routingStrategyArgs(routingStrategyArgs: JsonField) = apply { + this.routingStrategyArgs = routingStrategyArgs + } + + fun timeout(timeout: Double?) = timeout(JsonField.ofNullable(timeout)) + + /** + * Alias for [Builder.timeout]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun timeout(timeout: Double) = timeout(timeout as Double?) + + /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ + fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RouterSettings]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RouterSettings = + RouterSettings( + allowedFails, + (contextWindowFallbacks ?: JsonMissing.of()).map { it.toImmutable() }, + cooldownTime, + (fallbacks ?: JsonMissing.of()).map { it.toImmutable() }, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): RouterSettings = apply { + if (validated) { + return@apply + } + + allowedFails() + contextWindowFallbacks().ifPresent { it.forEach { it.validate() } } + cooldownTime() + fallbacks().ifPresent { it.forEach { it.validate() } } + maxRetries() + modelGroupAlias().ifPresent { it.validate() } + modelGroupRetryPolicy().ifPresent { it.validate() } + numRetries() + retryAfter() + routingStrategy() + routingStrategyArgs().ifPresent { it.validate() } + timeout() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (allowedFails.asKnown().isPresent) 1 else 0) + + (contextWindowFallbacks.asKnown().getOrNull()?.sumOf { it.validity().toInt() } + ?: 0) + + (if (cooldownTime.asKnown().isPresent) 1 else 0) + + (fallbacks.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (maxRetries.asKnown().isPresent) 1 else 0) + + (modelGroupAlias.asKnown().getOrNull()?.validity() ?: 0) + + (modelGroupRetryPolicy.asKnown().getOrNull()?.validity() ?: 0) + + (if (numRetries.asKnown().isPresent) 1 else 0) + + (if (retryAfter.asKnown().isPresent) 1 else 0) + + (if (routingStrategy.asKnown().isPresent) 1 else 0) + + (routingStrategyArgs.asKnown().getOrNull()?.validity() ?: 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + class ContextWindowFallback + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ContextWindowFallback]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ContextWindowFallback]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(contextWindowFallback: ContextWindowFallback) = apply { + additionalProperties = contextWindowFallback.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ContextWindowFallback]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ContextWindowFallback = + ContextWindowFallback(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ContextWindowFallback = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ContextWindowFallback && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ContextWindowFallback{additionalProperties=$additionalProperties}" + } + + class Fallback + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Fallback]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Fallback]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fallback: Fallback) = apply { + additionalProperties = fallback.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Fallback]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Fallback = Fallback(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Fallback = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Fallback && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Fallback{additionalProperties=$additionalProperties}" + } + + class ModelGroupAlias + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelGroupAlias]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelGroupAlias]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelGroupAlias: ModelGroupAlias) = apply { + additionalProperties = modelGroupAlias.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelGroupAlias]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelGroupAlias = ModelGroupAlias(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelGroupAlias = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelGroupAlias && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelGroupAlias{additionalProperties=$additionalProperties}" + } + + class ModelGroupRetryPolicy + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ModelGroupRetryPolicy]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelGroupRetryPolicy]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelGroupRetryPolicy: ModelGroupRetryPolicy) = apply { + additionalProperties = modelGroupRetryPolicy.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelGroupRetryPolicy]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelGroupRetryPolicy = + ModelGroupRetryPolicy(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelGroupRetryPolicy = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelGroupRetryPolicy && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ModelGroupRetryPolicy{additionalProperties=$additionalProperties}" + } + + class RoutingStrategyArgs + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RoutingStrategyArgs]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoutingStrategyArgs]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(routingStrategyArgs: RoutingStrategyArgs) = apply { + additionalProperties = routingStrategyArgs.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RoutingStrategyArgs]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RoutingStrategyArgs = + RoutingStrategyArgs(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): RoutingStrategyArgs = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RoutingStrategyArgs && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RoutingStrategyArgs{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RouterSettings && + allowedFails == other.allowedFails && + contextWindowFallbacks == other.contextWindowFallbacks && + cooldownTime == other.cooldownTime && + fallbacks == other.fallbacks && + maxRetries == other.maxRetries && + modelGroupAlias == other.modelGroupAlias && + modelGroupRetryPolicy == other.modelGroupRetryPolicy && + numRetries == other.numRetries && + retryAfter == other.retryAfter && + routingStrategy == other.routingStrategy && + routingStrategyArgs == other.routingStrategyArgs && + timeout == other.timeout && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + allowedFails, + contextWindowFallbacks, + cooldownTime, + fallbacks, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RouterSettings{allowedFails=$allowedFails, contextWindowFallbacks=$contextWindowFallbacks, cooldownTime=$cooldownTime, fallbacks=$fallbacks, maxRetries=$maxRetries, modelGroupAlias=$modelGroupAlias, modelGroupRetryPolicy=$modelGroupRetryPolicy, numRetries=$numRetries, retryAfter=$retryAfter, routingStrategy=$routingStrategy, routingStrategyArgs=$routingStrategyArgs, timeout=$timeout, additionalProperties=$additionalProperties}" + } + + class RpmLimitType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GUARANTEED_THROUGHPUT = of("guaranteed_throughput") + + @JvmField val BEST_EFFORT_THROUGHPUT = of("best_effort_throughput") + + @JvmField val DYNAMIC = of("dynamic") + + @JvmStatic fun of(value: String) = RpmLimitType(JsonField.of(value)) + } + + /** An enum containing [RpmLimitType]'s known values. */ + enum class Known { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + } + + /** + * An enum containing [RpmLimitType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [RpmLimitType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + /** + * An enum member indicating that [RpmLimitType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GUARANTEED_THROUGHPUT -> Value.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Value.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Value.DYNAMIC + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + GUARANTEED_THROUGHPUT -> Known.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Known.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Known.DYNAMIC + else -> throw HanzoInvalidDataException("Unknown RpmLimitType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): RpmLimitType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RpmLimitType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class TpmLimitType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GUARANTEED_THROUGHPUT = of("guaranteed_throughput") + + @JvmField val BEST_EFFORT_THROUGHPUT = of("best_effort_throughput") + + @JvmField val DYNAMIC = of("dynamic") + + @JvmStatic fun of(value: String) = TpmLimitType(JsonField.of(value)) + } + + /** An enum containing [TpmLimitType]'s known values. */ + enum class Known { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + } + + /** + * An enum containing [TpmLimitType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [TpmLimitType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + /** + * An enum member indicating that [TpmLimitType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GUARANTEED_THROUGHPUT -> Value.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Value.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Value.DYNAMIC + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + GUARANTEED_THROUGHPUT -> Known.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Known.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Known.DYNAMIC + else -> throw HanzoInvalidDataException("Unknown TpmLimitType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): TpmLimitType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TpmLimitType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GenerateKeyResponse && + key == other.key && + token == other.token && + aliases == other.aliases && + allowedCacheControls == other.allowedCacheControls && + allowedPassthroughRoutes == other.allowedPassthroughRoutes && + allowedRoutes == other.allowedRoutes && + allowedVectorStoreIndexes == other.allowedVectorStoreIndexes && + blocked == other.blocked && + budgetDuration == other.budgetDuration && + budgetId == other.budgetId && + config == other.config && + createdAt == other.createdAt && + createdBy == other.createdBy && + duration == other.duration && + enforcedParams == other.enforcedParams && + expires == other.expires && + guardrails == other.guardrails && + keyAlias == other.keyAlias && + keyName == other.keyName && + litellmBudgetTable == other.litellmBudgetTable && + maxBudget == other.maxBudget && + maxParallelRequests == other.maxParallelRequests && + metadata == other.metadata && + modelMaxBudget == other.modelMaxBudget && + modelRpmLimit == other.modelRpmLimit && + modelTpmLimit == other.modelTpmLimit && + models == other.models && + objectPermission == other.objectPermission && + organizationId == other.organizationId && + permissions == other.permissions && + prompts == other.prompts && + routerSettings == other.routerSettings && + rpmLimit == other.rpmLimit && + rpmLimitType == other.rpmLimitType && + spend == other.spend && + tags == other.tags && + teamId == other.teamId && + tokenId == other.tokenId && + tpmLimit == other.tpmLimit && + tpmLimitType == other.tpmLimitType && + updatedAt == other.updatedAt && + updatedBy == other.updatedBy && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + key, + token, + aliases, + allowedCacheControls, + allowedPassthroughRoutes, + allowedRoutes, + allowedVectorStoreIndexes, + blocked, + budgetDuration, + budgetId, + config, + createdAt, + createdBy, + duration, + enforcedParams, + expires, + guardrails, + keyAlias, + keyName, + litellmBudgetTable, + maxBudget, + maxParallelRequests, + metadata, + modelMaxBudget, + modelRpmLimit, + modelTpmLimit, + models, + objectPermission, + organizationId, + permissions, + prompts, + routerSettings, + rpmLimit, + rpmLimitType, + spend, + tags, + teamId, + tokenId, + tpmLimit, + tpmLimitType, + updatedAt, + updatedBy, + userId, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "GenerateKeyResponse{expires=$expires, key=$key, token=$token, aliases=$aliases, allowedCacheControls=$allowedCacheControls, blocked=$blocked, budgetDuration=$budgetDuration, budgetId=$budgetId, config=$config, createdBy=$createdBy, duration=$duration, enforcedParams=$enforcedParams, guardrails=$guardrails, keyAlias=$keyAlias, keyName=$keyName, llmBudgetTable=$llmBudgetTable, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelRpmLimit=$modelRpmLimit, modelTpmLimit=$modelTpmLimit, models=$models, permissions=$permissions, rpmLimit=$rpmLimit, spend=$spend, tags=$tags, teamId=$teamId, tokenId=$tokenId, tpmLimit=$tpmLimit, updatedBy=$updatedBy, userId=$userId, additionalProperties=$additionalProperties}" + "GenerateKeyResponse{key=$key, token=$token, aliases=$aliases, allowedCacheControls=$allowedCacheControls, allowedPassthroughRoutes=$allowedPassthroughRoutes, allowedRoutes=$allowedRoutes, allowedVectorStoreIndexes=$allowedVectorStoreIndexes, blocked=$blocked, budgetDuration=$budgetDuration, budgetId=$budgetId, config=$config, createdAt=$createdAt, createdBy=$createdBy, duration=$duration, enforcedParams=$enforcedParams, expires=$expires, guardrails=$guardrails, keyAlias=$keyAlias, keyName=$keyName, litellmBudgetTable=$litellmBudgetTable, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelRpmLimit=$modelRpmLimit, modelTpmLimit=$modelTpmLimit, models=$models, objectPermission=$objectPermission, organizationId=$organizationId, permissions=$permissions, prompts=$prompts, routerSettings=$routerSettings, rpmLimit=$rpmLimit, rpmLimitType=$rpmLimitType, spend=$spend, tags=$tags, teamId=$teamId, tokenId=$tokenId, tpmLimit=$tpmLimit, tpmLimitType=$tpmLimitType, updatedAt=$updatedAt, updatedBy=$updatedBy, userId=$userId, additionalProperties=$additionalProperties}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyBlockParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyBlockParams.kt index 9c52f0be..7de583c7 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyBlockParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyBlockParams.kt @@ -28,25 +28,27 @@ import kotlin.jvm.optionals.getOrNull */ class KeyBlockParams private constructor( - private val llmChangedBy: String?, + private val litellmChangedBy: String?, private val blockKeyRequest: BlockKeyRequest, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { /** - * The llm-changed-by header enables tracking of actions performed by authorized users on behalf - * of other users, providing an audit trail for accountability + * The litellm-changed-by header enables tracking of actions performed by authorized users on + * behalf of other users, providing an audit trail for accountability */ - fun llmChangedBy(): Optional = Optional.ofNullable(llmChangedBy) + fun litellmChangedBy(): Optional = Optional.ofNullable(litellmChangedBy) fun blockKeyRequest(): BlockKeyRequest = blockKeyRequest fun _additionalBodyProperties(): Map = blockKeyRequest._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -67,27 +69,30 @@ private constructor( /** A builder for [KeyBlockParams]. */ class Builder internal constructor() { - private var llmChangedBy: String? = null + private var litellmChangedBy: String? = null private var blockKeyRequest: BlockKeyRequest? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(keyBlockParams: KeyBlockParams) = apply { - llmChangedBy = keyBlockParams.llmChangedBy + litellmChangedBy = keyBlockParams.litellmChangedBy blockKeyRequest = keyBlockParams.blockKeyRequest additionalHeaders = keyBlockParams.additionalHeaders.toBuilder() additionalQueryParams = keyBlockParams.additionalQueryParams.toBuilder() } /** - * The llm-changed-by header enables tracking of actions performed by authorized users on - * behalf of other users, providing an audit trail for accountability + * The litellm-changed-by header enables tracking of actions performed by authorized users + * on behalf of other users, providing an audit trail for accountability */ - fun llmChangedBy(llmChangedBy: String?) = apply { this.llmChangedBy = llmChangedBy } + fun litellmChangedBy(litellmChangedBy: String?) = apply { + this.litellmChangedBy = litellmChangedBy + } - /** Alias for calling [Builder.llmChangedBy] with `llmChangedBy.orElse(null)`. */ - fun llmChangedBy(llmChangedBy: Optional) = llmChangedBy(llmChangedBy.getOrNull()) + /** Alias for calling [Builder.litellmChangedBy] with `litellmChangedBy.orElse(null)`. */ + fun litellmChangedBy(litellmChangedBy: Optional) = + litellmChangedBy(litellmChangedBy.getOrNull()) fun blockKeyRequest(blockKeyRequest: BlockKeyRequest) = apply { this.blockKeyRequest = blockKeyRequest @@ -205,19 +210,19 @@ private constructor( */ fun build(): KeyBlockParams = KeyBlockParams( - llmChangedBy, + litellmChangedBy, checkRequired("blockKeyRequest", blockKeyRequest), additionalHeaders.build(), additionalQueryParams.build(), ) } - @JvmSynthetic internal fun _body(): BlockKeyRequest = blockKeyRequest + fun _body(): BlockKeyRequest = blockKeyRequest override fun _headers(): Headers = Headers.builder() .apply { - llmChangedBy?.let { put("llm-changed-by", it) } + litellmChangedBy?.let { put("litellm-changed-by", it) } putAll(additionalHeaders) } .build() @@ -229,11 +234,16 @@ private constructor( return true } - return /* spotless:off */ other is KeyBlockParams && llmChangedBy == other.llmChangedBy && blockKeyRequest == other.blockKeyRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is KeyBlockParams && + litellmChangedBy == other.litellmChangedBy && + blockKeyRequest == other.blockKeyRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(llmChangedBy, blockKeyRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(litellmChangedBy, blockKeyRequest, additionalHeaders, additionalQueryParams) override fun toString() = - "KeyBlockParams{llmChangedBy=$llmChangedBy, blockKeyRequest=$blockKeyRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "KeyBlockParams{litellmChangedBy=$litellmChangedBy, blockKeyRequest=$blockKeyRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyBlockResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyBlockResponse.kt index 20730518..90a72357 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyBlockResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyBlockResponse.kt @@ -8,7 +8,9 @@ import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonField import ai.hanzo.api.core.JsonMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.core.allMaxBy import ai.hanzo.api.core.checkKnown +import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.getOrThrow import ai.hanzo.api.core.toImmutable import ai.hanzo.api.errors.HanzoInvalidDataException @@ -30,28 +32,38 @@ import java.util.Optional import kotlin.jvm.optionals.getOrNull class KeyBlockResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val token: JsonField, - private val aliases: JsonValue, + private val aliases: JsonField, private val allowedCacheControls: JsonField>, + private val allowedRoutes: JsonField>, + private val autoRotate: JsonField, private val blocked: JsonField, private val budgetDuration: JsonField, private val budgetResetAt: JsonField, - private val config: JsonValue, + private val config: JsonField, private val createdAt: JsonField, private val createdBy: JsonField, private val expires: JsonField, private val keyAlias: JsonField, private val keyName: JsonField, - private val llmBudgetTable: JsonValue, + private val keyRotationAt: JsonField, + private val lastRotationAt: JsonField, + private val litellmBudgetTable: JsonField, private val maxBudget: JsonField, private val maxParallelRequests: JsonField, - private val metadata: JsonValue, - private val modelMaxBudget: JsonValue, - private val modelSpend: JsonValue, + private val metadata: JsonField, + private val modelMaxBudget: JsonField, + private val modelSpend: JsonField, private val models: JsonField>, + private val objectPermission: JsonField, + private val objectPermissionId: JsonField, private val orgId: JsonField, - private val permissions: JsonValue, + private val permissions: JsonField, + private val rotationCount: JsonField, + private val rotationInterval: JsonField, + private val routerSettings: JsonField, private val rpmLimit: JsonField, private val softBudgetCooldown: JsonField, private val spend: JsonField, @@ -66,10 +78,16 @@ private constructor( @JsonCreator private constructor( @JsonProperty("token") @ExcludeMissing token: JsonField = JsonMissing.of(), - @JsonProperty("aliases") @ExcludeMissing aliases: JsonValue = JsonMissing.of(), + @JsonProperty("aliases") @ExcludeMissing aliases: JsonField = JsonMissing.of(), @JsonProperty("allowed_cache_controls") @ExcludeMissing allowedCacheControls: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_routes") + @ExcludeMissing + allowedRoutes: JsonField> = JsonMissing.of(), + @JsonProperty("auto_rotate") + @ExcludeMissing + autoRotate: JsonField = JsonMissing.of(), @JsonProperty("blocked") @ExcludeMissing blocked: JsonField = JsonMissing.of(), @JsonProperty("budget_duration") @ExcludeMissing @@ -77,7 +95,7 @@ private constructor( @JsonProperty("budget_reset_at") @ExcludeMissing budgetResetAt: JsonField = JsonMissing.of(), - @JsonProperty("config") @ExcludeMissing config: JsonValue = JsonMissing.of(), + @JsonProperty("config") @ExcludeMissing config: JsonField = JsonMissing.of(), @JsonProperty("created_at") @ExcludeMissing createdAt: JsonField = JsonMissing.of(), @@ -85,23 +103,48 @@ private constructor( @JsonProperty("expires") @ExcludeMissing expires: JsonField = JsonMissing.of(), @JsonProperty("key_alias") @ExcludeMissing keyAlias: JsonField = JsonMissing.of(), @JsonProperty("key_name") @ExcludeMissing keyName: JsonField = JsonMissing.of(), - @JsonProperty("llm_budget_table") + @JsonProperty("key_rotation_at") + @ExcludeMissing + keyRotationAt: JsonField = JsonMissing.of(), + @JsonProperty("last_rotation_at") + @ExcludeMissing + lastRotationAt: JsonField = JsonMissing.of(), + @JsonProperty("litellm_budget_table") @ExcludeMissing - llmBudgetTable: JsonValue = JsonMissing.of(), + litellmBudgetTable: JsonField = JsonMissing.of(), @JsonProperty("max_budget") @ExcludeMissing maxBudget: JsonField = JsonMissing.of(), @JsonProperty("max_parallel_requests") @ExcludeMissing maxParallelRequests: JsonField = JsonMissing.of(), - @JsonProperty("metadata") @ExcludeMissing metadata: JsonValue = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), @JsonProperty("model_max_budget") @ExcludeMissing - modelMaxBudget: JsonValue = JsonMissing.of(), - @JsonProperty("model_spend") @ExcludeMissing modelSpend: JsonValue = JsonMissing.of(), + modelMaxBudget: JsonField = JsonMissing.of(), + @JsonProperty("model_spend") + @ExcludeMissing + modelSpend: JsonField = JsonMissing.of(), @JsonProperty("models") @ExcludeMissing models: JsonField> = JsonMissing.of(), + @JsonProperty("object_permission") + @ExcludeMissing + objectPermission: JsonField = JsonMissing.of(), + @JsonProperty("object_permission_id") + @ExcludeMissing + objectPermissionId: JsonField = JsonMissing.of(), @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), - @JsonProperty("permissions") @ExcludeMissing permissions: JsonValue = JsonMissing.of(), + @JsonProperty("permissions") + @ExcludeMissing + permissions: JsonField = JsonMissing.of(), + @JsonProperty("rotation_count") + @ExcludeMissing + rotationCount: JsonField = JsonMissing.of(), + @JsonProperty("rotation_interval") + @ExcludeMissing + rotationInterval: JsonField = JsonMissing.of(), + @JsonProperty("router_settings") + @ExcludeMissing + routerSettings: JsonField = JsonMissing.of(), @JsonProperty("rpm_limit") @ExcludeMissing rpmLimit: JsonField = JsonMissing.of(), @JsonProperty("soft_budget_cooldown") @ExcludeMissing @@ -118,6 +161,8 @@ private constructor( token, aliases, allowedCacheControls, + allowedRoutes, + autoRotate, blocked, budgetDuration, budgetResetAt, @@ -127,15 +172,22 @@ private constructor( expires, keyAlias, keyName, - llmBudgetTable, + keyRotationAt, + lastRotationAt, + litellmBudgetTable, maxBudget, maxParallelRequests, metadata, modelMaxBudget, modelSpend, models, + objectPermission, + objectPermissionId, orgId, permissions, + rotationCount, + rotationInterval, + routerSettings, rpmLimit, softBudgetCooldown, spend, @@ -151,158 +203,237 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun token(): Optional = Optional.ofNullable(token.getNullable("token")) + fun token(): Optional = token.getOptional("token") - @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonValue = aliases + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aliases(): Optional = aliases.getOptional("aliases") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun allowedCacheControls(): Optional> = - Optional.ofNullable(allowedCacheControls.getNullable("allowed_cache_controls")) + allowedCacheControls.getOptional("allowed_cache_controls") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedRoutes(): Optional> = allowedRoutes.getOptional("allowed_routes") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun autoRotate(): Optional = autoRotate.getOptional("auto_rotate") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun blocked(): Optional = Optional.ofNullable(blocked.getNullable("blocked")) + fun blocked(): Optional = blocked.getOptional("blocked") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetDuration(): Optional = - Optional.ofNullable(budgetDuration.getNullable("budget_duration")) + fun budgetDuration(): Optional = budgetDuration.getOptional("budget_duration") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetResetAt(): Optional = - Optional.ofNullable(budgetResetAt.getNullable("budget_reset_at")) + fun budgetResetAt(): Optional = budgetResetAt.getOptional("budget_reset_at") - @JsonProperty("config") @ExcludeMissing fun _config(): JsonValue = config + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun config(): Optional = config.getOptional("config") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun createdAt(): Optional = - Optional.ofNullable(createdAt.getNullable("created_at")) + fun createdAt(): Optional = createdAt.getOptional("created_at") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun createdBy(): Optional = Optional.ofNullable(createdBy.getNullable("created_by")) + fun createdBy(): Optional = createdBy.getOptional("created_by") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun expires(): Optional = Optional.ofNullable(expires.getNullable("expires")) + fun expires(): Optional = expires.getOptional("expires") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun keyAlias(): Optional = Optional.ofNullable(keyAlias.getNullable("key_alias")) + fun keyAlias(): Optional = keyAlias.getOptional("key_alias") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun keyName(): Optional = Optional.ofNullable(keyName.getNullable("key_name")) + fun keyName(): Optional = keyName.getOptional("key_name") - @JsonProperty("llm_budget_table") - @ExcludeMissing - fun _llmBudgetTable(): JsonValue = llmBudgetTable + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun keyRotationAt(): Optional = keyRotationAt.getOptional("key_rotation_at") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lastRotationAt(): Optional = lastRotationAt.getOptional("last_rotation_at") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun litellmBudgetTable(): Optional = + litellmBudgetTable.getOptional("litellm_budget_table") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun maxBudget(): Optional = Optional.ofNullable(maxBudget.getNullable("max_budget")) + fun maxBudget(): Optional = maxBudget.getOptional("max_budget") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun maxParallelRequests(): Optional = - Optional.ofNullable(maxParallelRequests.getNullable("max_parallel_requests")) + maxParallelRequests.getOptional("max_parallel_requests") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonValue = metadata + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelMaxBudget(): Optional = modelMaxBudget.getOptional("model_max_budget") - @JsonProperty("model_max_budget") - @ExcludeMissing - fun _modelMaxBudget(): JsonValue = modelMaxBudget + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelSpend(): Optional = modelSpend.getOptional("model_spend") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun models(): Optional> = models.getOptional("models") - @JsonProperty("model_spend") @ExcludeMissing fun _modelSpend(): JsonValue = modelSpend + /** + * Represents a LiteLLM_ObjectPermissionTable record + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun objectPermission(): Optional = + objectPermission.getOptional("object_permission") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun objectPermissionId(): Optional = + objectPermissionId.getOptional("object_permission_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun orgId(): Optional = orgId.getOptional("org_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun permissions(): Optional = permissions.getOptional("permissions") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun models(): Optional> = Optional.ofNullable(models.getNullable("models")) + fun rotationCount(): Optional = rotationCount.getOptional("rotation_count") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun orgId(): Optional = Optional.ofNullable(orgId.getNullable("org_id")) + fun rotationInterval(): Optional = rotationInterval.getOptional("rotation_interval") - @JsonProperty("permissions") @ExcludeMissing fun _permissions(): JsonValue = permissions + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routerSettings(): Optional = routerSettings.getOptional("router_settings") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rpmLimit(): Optional = Optional.ofNullable(rpmLimit.getNullable("rpm_limit")) + fun rpmLimit(): Optional = rpmLimit.getOptional("rpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun softBudgetCooldown(): Optional = - Optional.ofNullable(softBudgetCooldown.getNullable("soft_budget_cooldown")) + softBudgetCooldown.getOptional("soft_budget_cooldown") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spend(): Optional = Optional.ofNullable(spend.getNullable("spend")) + fun spend(): Optional = spend.getOptional("spend") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun teamId(): Optional = Optional.ofNullable(teamId.getNullable("team_id")) + fun teamId(): Optional = teamId.getOptional("team_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tpmLimit(): Optional = Optional.ofNullable(tpmLimit.getNullable("tpm_limit")) + fun tpmLimit(): Optional = tpmLimit.getOptional("tpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun updatedAt(): Optional = - Optional.ofNullable(updatedAt.getNullable("updated_at")) + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun updatedBy(): Optional = Optional.ofNullable(updatedBy.getNullable("updated_by")) + fun updatedBy(): Optional = updatedBy.getOptional("updated_by") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) + fun userId(): Optional = userId.getOptional("user_id") /** * Returns the raw JSON value of [token]. @@ -311,6 +442,13 @@ private constructor( */ @JsonProperty("token") @ExcludeMissing fun _token(): JsonField = token + /** + * Returns the raw JSON value of [aliases]. + * + * Unlike [aliases], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonField = aliases + /** * Returns the raw JSON value of [allowedCacheControls]. * @@ -321,6 +459,22 @@ private constructor( @ExcludeMissing fun _allowedCacheControls(): JsonField> = allowedCacheControls + /** + * Returns the raw JSON value of [allowedRoutes]. + * + * Unlike [allowedRoutes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("allowed_routes") + @ExcludeMissing + fun _allowedRoutes(): JsonField> = allowedRoutes + + /** + * Returns the raw JSON value of [autoRotate]. + * + * Unlike [autoRotate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("auto_rotate") @ExcludeMissing fun _autoRotate(): JsonField = autoRotate + /** * Returns the raw JSON value of [blocked]. * @@ -346,6 +500,13 @@ private constructor( @ExcludeMissing fun _budgetResetAt(): JsonField = budgetResetAt + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config") @ExcludeMissing fun _config(): JsonField = config + /** * Returns the raw JSON value of [createdAt]. * @@ -383,6 +544,34 @@ private constructor( */ @JsonProperty("key_name") @ExcludeMissing fun _keyName(): JsonField = keyName + /** + * Returns the raw JSON value of [keyRotationAt]. + * + * Unlike [keyRotationAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("key_rotation_at") + @ExcludeMissing + fun _keyRotationAt(): JsonField = keyRotationAt + + /** + * Returns the raw JSON value of [lastRotationAt]. + * + * Unlike [lastRotationAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("last_rotation_at") + @ExcludeMissing + fun _lastRotationAt(): JsonField = lastRotationAt + + /** + * Returns the raw JSON value of [litellmBudgetTable]. + * + * Unlike [litellmBudgetTable], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("litellm_budget_table") + @ExcludeMissing + fun _litellmBudgetTable(): JsonField = litellmBudgetTable + /** * Returns the raw JSON value of [maxBudget]. * @@ -400,6 +589,31 @@ private constructor( @ExcludeMissing fun _maxParallelRequests(): JsonField = maxParallelRequests + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [modelMaxBudget]. + * + * Unlike [modelMaxBudget], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model_max_budget") + @ExcludeMissing + fun _modelMaxBudget(): JsonField = modelMaxBudget + + /** + * Returns the raw JSON value of [modelSpend]. + * + * Unlike [modelSpend], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model_spend") + @ExcludeMissing + fun _modelSpend(): JsonField = modelSpend + /** * Returns the raw JSON value of [models]. * @@ -407,6 +621,26 @@ private constructor( */ @JsonProperty("models") @ExcludeMissing fun _models(): JsonField> = models + /** + * Returns the raw JSON value of [objectPermission]. + * + * Unlike [objectPermission], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("object_permission") + @ExcludeMissing + fun _objectPermission(): JsonField = objectPermission + + /** + * Returns the raw JSON value of [objectPermissionId]. + * + * Unlike [objectPermissionId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("object_permission_id") + @ExcludeMissing + fun _objectPermissionId(): JsonField = objectPermissionId + /** * Returns the raw JSON value of [orgId]. * @@ -414,6 +648,43 @@ private constructor( */ @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + /** + * Returns the raw JSON value of [permissions]. + * + * Unlike [permissions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permissions") + @ExcludeMissing + fun _permissions(): JsonField = permissions + + /** + * Returns the raw JSON value of [rotationCount]. + * + * Unlike [rotationCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("rotation_count") + @ExcludeMissing + fun _rotationCount(): JsonField = rotationCount + + /** + * Returns the raw JSON value of [rotationInterval]. + * + * Unlike [rotationInterval], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("rotation_interval") + @ExcludeMissing + fun _rotationInterval(): JsonField = rotationInterval + + /** + * Returns the raw JSON value of [routerSettings]. + * + * Unlike [routerSettings], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("router_settings") + @ExcludeMissing + fun _routerSettings(): JsonField = routerSettings + /** * Returns the raw JSON value of [rpmLimit]. * @@ -497,26 +768,35 @@ private constructor( class Builder internal constructor() { private var token: JsonField = JsonMissing.of() - private var aliases: JsonValue = JsonMissing.of() + private var aliases: JsonField = JsonMissing.of() private var allowedCacheControls: JsonField>? = null + private var allowedRoutes: JsonField>? = null + private var autoRotate: JsonField = JsonMissing.of() private var blocked: JsonField = JsonMissing.of() private var budgetDuration: JsonField = JsonMissing.of() private var budgetResetAt: JsonField = JsonMissing.of() - private var config: JsonValue = JsonMissing.of() + private var config: JsonField = JsonMissing.of() private var createdAt: JsonField = JsonMissing.of() private var createdBy: JsonField = JsonMissing.of() private var expires: JsonField = JsonMissing.of() private var keyAlias: JsonField = JsonMissing.of() private var keyName: JsonField = JsonMissing.of() - private var llmBudgetTable: JsonValue = JsonMissing.of() + private var keyRotationAt: JsonField = JsonMissing.of() + private var lastRotationAt: JsonField = JsonMissing.of() + private var litellmBudgetTable: JsonField = JsonMissing.of() private var maxBudget: JsonField = JsonMissing.of() private var maxParallelRequests: JsonField = JsonMissing.of() - private var metadata: JsonValue = JsonMissing.of() - private var modelMaxBudget: JsonValue = JsonMissing.of() - private var modelSpend: JsonValue = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var modelMaxBudget: JsonField = JsonMissing.of() + private var modelSpend: JsonField = JsonMissing.of() private var models: JsonField>? = null + private var objectPermission: JsonField = JsonMissing.of() + private var objectPermissionId: JsonField = JsonMissing.of() private var orgId: JsonField = JsonMissing.of() - private var permissions: JsonValue = JsonMissing.of() + private var permissions: JsonField = JsonMissing.of() + private var rotationCount: JsonField = JsonMissing.of() + private var rotationInterval: JsonField = JsonMissing.of() + private var routerSettings: JsonField = JsonMissing.of() private var rpmLimit: JsonField = JsonMissing.of() private var softBudgetCooldown: JsonField = JsonMissing.of() private var spend: JsonField = JsonMissing.of() @@ -532,6 +812,8 @@ private constructor( token = keyBlockResponse.token aliases = keyBlockResponse.aliases allowedCacheControls = keyBlockResponse.allowedCacheControls.map { it.toMutableList() } + allowedRoutes = keyBlockResponse.allowedRoutes.map { it.toMutableList() } + autoRotate = keyBlockResponse.autoRotate blocked = keyBlockResponse.blocked budgetDuration = keyBlockResponse.budgetDuration budgetResetAt = keyBlockResponse.budgetResetAt @@ -541,15 +823,22 @@ private constructor( expires = keyBlockResponse.expires keyAlias = keyBlockResponse.keyAlias keyName = keyBlockResponse.keyName - llmBudgetTable = keyBlockResponse.llmBudgetTable + keyRotationAt = keyBlockResponse.keyRotationAt + lastRotationAt = keyBlockResponse.lastRotationAt + litellmBudgetTable = keyBlockResponse.litellmBudgetTable maxBudget = keyBlockResponse.maxBudget maxParallelRequests = keyBlockResponse.maxParallelRequests metadata = keyBlockResponse.metadata modelMaxBudget = keyBlockResponse.modelMaxBudget modelSpend = keyBlockResponse.modelSpend models = keyBlockResponse.models.map { it.toMutableList() } + objectPermission = keyBlockResponse.objectPermission + objectPermissionId = keyBlockResponse.objectPermissionId orgId = keyBlockResponse.orgId permissions = keyBlockResponse.permissions + rotationCount = keyBlockResponse.rotationCount + rotationInterval = keyBlockResponse.rotationInterval + routerSettings = keyBlockResponse.routerSettings rpmLimit = keyBlockResponse.rpmLimit softBudgetCooldown = keyBlockResponse.softBudgetCooldown spend = keyBlockResponse.spend @@ -574,7 +863,15 @@ private constructor( */ fun token(token: JsonField) = apply { this.token = token } - fun aliases(aliases: JsonValue) = apply { this.aliases = aliases } + fun aliases(aliases: Aliases) = aliases(JsonField.of(aliases)) + + /** + * Sets [Builder.aliases] to an arbitrary JSON value. + * + * You should usually call [Builder.aliases] with a well-typed [Aliases] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun aliases(aliases: JsonField) = apply { this.aliases = aliases } fun allowedCacheControls(allowedCacheControls: List?) = allowedCacheControls(JsonField.ofNullable(allowedCacheControls)) @@ -609,6 +906,57 @@ private constructor( } } + fun allowedRoutes(allowedRoutes: List?) = + allowedRoutes(JsonField.ofNullable(allowedRoutes)) + + /** Alias for calling [Builder.allowedRoutes] with `allowedRoutes.orElse(null)`. */ + fun allowedRoutes(allowedRoutes: Optional>) = + allowedRoutes(allowedRoutes.getOrNull()) + + /** + * Sets [Builder.allowedRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedRoutes] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun allowedRoutes(allowedRoutes: JsonField>) = apply { + this.allowedRoutes = allowedRoutes.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [allowedRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedRoute(allowedRoute: JsonValue) = apply { + allowedRoutes = + (allowedRoutes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedRoutes", it).add(allowedRoute) + } + } + + fun autoRotate(autoRotate: Boolean?) = autoRotate(JsonField.ofNullable(autoRotate)) + + /** + * Alias for [Builder.autoRotate]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun autoRotate(autoRotate: Boolean) = autoRotate(autoRotate as Boolean?) + + /** Alias for calling [Builder.autoRotate] with `autoRotate.orElse(null)`. */ + fun autoRotate(autoRotate: Optional) = autoRotate(autoRotate.getOrNull()) + + /** + * Sets [Builder.autoRotate] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRotate] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun autoRotate(autoRotate: JsonField) = apply { this.autoRotate = autoRotate } + fun blocked(blocked: Boolean?) = blocked(JsonField.ofNullable(blocked)) /** @@ -665,7 +1013,15 @@ private constructor( this.budgetResetAt = budgetResetAt } - fun config(config: JsonValue) = apply { this.config = config } + fun config(config: Config) = config(JsonField.of(config)) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [Config] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun config(config: JsonField) = apply { this.config = config } fun createdAt(createdAt: OffsetDateTime?) = createdAt(JsonField.ofNullable(createdAt)) @@ -741,8 +1097,60 @@ private constructor( */ fun keyName(keyName: JsonField) = apply { this.keyName = keyName } - fun llmBudgetTable(llmBudgetTable: JsonValue) = apply { - this.llmBudgetTable = llmBudgetTable + fun keyRotationAt(keyRotationAt: OffsetDateTime?) = + keyRotationAt(JsonField.ofNullable(keyRotationAt)) + + /** Alias for calling [Builder.keyRotationAt] with `keyRotationAt.orElse(null)`. */ + fun keyRotationAt(keyRotationAt: Optional) = + keyRotationAt(keyRotationAt.getOrNull()) + + /** + * Sets [Builder.keyRotationAt] to an arbitrary JSON value. + * + * You should usually call [Builder.keyRotationAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun keyRotationAt(keyRotationAt: JsonField) = apply { + this.keyRotationAt = keyRotationAt + } + + fun lastRotationAt(lastRotationAt: OffsetDateTime?) = + lastRotationAt(JsonField.ofNullable(lastRotationAt)) + + /** Alias for calling [Builder.lastRotationAt] with `lastRotationAt.orElse(null)`. */ + fun lastRotationAt(lastRotationAt: Optional) = + lastRotationAt(lastRotationAt.getOrNull()) + + /** + * Sets [Builder.lastRotationAt] to an arbitrary JSON value. + * + * You should usually call [Builder.lastRotationAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun lastRotationAt(lastRotationAt: JsonField) = apply { + this.lastRotationAt = lastRotationAt + } + + fun litellmBudgetTable(litellmBudgetTable: LitellmBudgetTable?) = + litellmBudgetTable(JsonField.ofNullable(litellmBudgetTable)) + + /** + * Alias for calling [Builder.litellmBudgetTable] with `litellmBudgetTable.orElse(null)`. + */ + fun litellmBudgetTable(litellmBudgetTable: Optional) = + litellmBudgetTable(litellmBudgetTable.getOrNull()) + + /** + * Sets [Builder.litellmBudgetTable] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmBudgetTable] with a well-typed + * [LitellmBudgetTable] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun litellmBudgetTable(litellmBudgetTable: JsonField) = apply { + this.litellmBudgetTable = litellmBudgetTable } fun maxBudget(maxBudget: Double?) = maxBudget(JsonField.ofNullable(maxBudget)) @@ -794,13 +1202,41 @@ private constructor( this.maxParallelRequests = maxParallelRequests } - fun metadata(metadata: JsonValue) = apply { this.metadata = metadata } + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun modelMaxBudget(modelMaxBudget: ModelMaxBudget) = + modelMaxBudget(JsonField.of(modelMaxBudget)) - fun modelMaxBudget(modelMaxBudget: JsonValue) = apply { + /** + * Sets [Builder.modelMaxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.modelMaxBudget] with a well-typed [ModelMaxBudget] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelMaxBudget(modelMaxBudget: JsonField) = apply { this.modelMaxBudget = modelMaxBudget } - fun modelSpend(modelSpend: JsonValue) = apply { this.modelSpend = modelSpend } + fun modelSpend(modelSpend: ModelSpend) = modelSpend(JsonField.of(modelSpend)) + + /** + * Sets [Builder.modelSpend] to an arbitrary JSON value. + * + * You should usually call [Builder.modelSpend] with a well-typed [ModelSpend] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelSpend(modelSpend: JsonField) = apply { this.modelSpend = modelSpend } fun models(models: List) = models(JsonField.of(models)) @@ -827,20 +1263,129 @@ private constructor( } } - fun orgId(orgId: String?) = orgId(JsonField.ofNullable(orgId)) + /** Represents a LiteLLM_ObjectPermissionTable record */ + fun objectPermission(objectPermission: ObjectPermission?) = + objectPermission(JsonField.ofNullable(objectPermission)) - /** Alias for calling [Builder.orgId] with `orgId.orElse(null)`. */ - fun orgId(orgId: Optional) = orgId(orgId.getOrNull()) + /** Alias for calling [Builder.objectPermission] with `objectPermission.orElse(null)`. */ + fun objectPermission(objectPermission: Optional) = + objectPermission(objectPermission.getOrNull()) /** - * Sets [Builder.orgId] to an arbitrary JSON value. + * Sets [Builder.objectPermission] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermission] with a well-typed [ObjectPermission] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun objectPermission(objectPermission: JsonField) = apply { + this.objectPermission = objectPermission + } + + fun objectPermissionId(objectPermissionId: String?) = + objectPermissionId(JsonField.ofNullable(objectPermissionId)) + + /** + * Alias for calling [Builder.objectPermissionId] with `objectPermissionId.orElse(null)`. + */ + fun objectPermissionId(objectPermissionId: Optional) = + objectPermissionId(objectPermissionId.getOrNull()) + + /** + * Sets [Builder.objectPermissionId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermissionId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectPermissionId(objectPermissionId: JsonField) = apply { + this.objectPermissionId = objectPermissionId + } + + fun orgId(orgId: String?) = orgId(JsonField.ofNullable(orgId)) + + /** Alias for calling [Builder.orgId] with `orgId.orElse(null)`. */ + fun orgId(orgId: Optional) = orgId(orgId.getOrNull()) + + /** + * Sets [Builder.orgId] to an arbitrary JSON value. * * You should usually call [Builder.orgId] with a well-typed [String] value instead. This * method is primarily for setting the field to an undocumented or not yet supported value. */ fun orgId(orgId: JsonField) = apply { this.orgId = orgId } - fun permissions(permissions: JsonValue) = apply { this.permissions = permissions } + fun permissions(permissions: Permissions) = permissions(JsonField.of(permissions)) + + /** + * Sets [Builder.permissions] to an arbitrary JSON value. + * + * You should usually call [Builder.permissions] with a well-typed [Permissions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun permissions(permissions: JsonField) = apply { + this.permissions = permissions + } + + fun rotationCount(rotationCount: Long?) = rotationCount(JsonField.ofNullable(rotationCount)) + + /** + * Alias for [Builder.rotationCount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun rotationCount(rotationCount: Long) = rotationCount(rotationCount as Long?) + + /** Alias for calling [Builder.rotationCount] with `rotationCount.orElse(null)`. */ + fun rotationCount(rotationCount: Optional) = rotationCount(rotationCount.getOrNull()) + + /** + * Sets [Builder.rotationCount] to an arbitrary JSON value. + * + * You should usually call [Builder.rotationCount] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rotationCount(rotationCount: JsonField) = apply { + this.rotationCount = rotationCount + } + + fun rotationInterval(rotationInterval: String?) = + rotationInterval(JsonField.ofNullable(rotationInterval)) + + /** Alias for calling [Builder.rotationInterval] with `rotationInterval.orElse(null)`. */ + fun rotationInterval(rotationInterval: Optional) = + rotationInterval(rotationInterval.getOrNull()) + + /** + * Sets [Builder.rotationInterval] to an arbitrary JSON value. + * + * You should usually call [Builder.rotationInterval] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rotationInterval(rotationInterval: JsonField) = apply { + this.rotationInterval = rotationInterval + } + + fun routerSettings(routerSettings: RouterSettings?) = + routerSettings(JsonField.ofNullable(routerSettings)) + + /** Alias for calling [Builder.routerSettings] with `routerSettings.orElse(null)`. */ + fun routerSettings(routerSettings: Optional) = + routerSettings(routerSettings.getOrNull()) + + /** + * Sets [Builder.routerSettings] to an arbitrary JSON value. + * + * You should usually call [Builder.routerSettings] with a well-typed [RouterSettings] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun routerSettings(routerSettings: JsonField) = apply { + this.routerSettings = routerSettings + } fun rpmLimit(rpmLimit: Long?) = rpmLimit(JsonField.ofNullable(rpmLimit)) @@ -989,6 +1534,8 @@ private constructor( token, aliases, (allowedCacheControls ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedRoutes ?: JsonMissing.of()).map { it.toImmutable() }, + autoRotate, blocked, budgetDuration, budgetResetAt, @@ -998,15 +1545,22 @@ private constructor( expires, keyAlias, keyName, - llmBudgetTable, + keyRotationAt, + lastRotationAt, + litellmBudgetTable, maxBudget, maxParallelRequests, metadata, modelMaxBudget, modelSpend, (models ?: JsonMissing.of()).map { it.toImmutable() }, + objectPermission, + objectPermissionId, orgId, permissions, + rotationCount, + rotationInterval, + routerSettings, rpmLimit, softBudgetCooldown, spend, @@ -1027,19 +1581,35 @@ private constructor( } token() + aliases().ifPresent { it.validate() } allowedCacheControls() + allowedRoutes() + autoRotate() blocked() budgetDuration() budgetResetAt() + config().ifPresent { it.validate() } createdAt() createdBy() expires().ifPresent { it.validate() } keyAlias() keyName() + keyRotationAt() + lastRotationAt() + litellmBudgetTable().ifPresent { it.validate() } maxBudget() maxParallelRequests() + metadata().ifPresent { it.validate() } + modelMaxBudget().ifPresent { it.validate() } + modelSpend().ifPresent { it.validate() } models() + objectPermission().ifPresent { it.validate() } + objectPermissionId() orgId() + permissions().ifPresent { it.validate() } + rotationCount() + rotationInterval() + routerSettings().ifPresent { it.validate() } rpmLimit() softBudgetCooldown() spend() @@ -1051,6 +1621,258 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (token.asKnown().isPresent) 1 else 0) + + (aliases.asKnown().getOrNull()?.validity() ?: 0) + + (allowedCacheControls.asKnown().getOrNull()?.size ?: 0) + + (allowedRoutes.asKnown().getOrNull()?.size ?: 0) + + (if (autoRotate.asKnown().isPresent) 1 else 0) + + (if (blocked.asKnown().isPresent) 1 else 0) + + (if (budgetDuration.asKnown().isPresent) 1 else 0) + + (if (budgetResetAt.asKnown().isPresent) 1 else 0) + + (config.asKnown().getOrNull()?.validity() ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (createdBy.asKnown().isPresent) 1 else 0) + + (expires.asKnown().getOrNull()?.validity() ?: 0) + + (if (keyAlias.asKnown().isPresent) 1 else 0) + + (if (keyName.asKnown().isPresent) 1 else 0) + + (if (keyRotationAt.asKnown().isPresent) 1 else 0) + + (if (lastRotationAt.asKnown().isPresent) 1 else 0) + + (litellmBudgetTable.asKnown().getOrNull()?.validity() ?: 0) + + (if (maxBudget.asKnown().isPresent) 1 else 0) + + (if (maxParallelRequests.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (modelMaxBudget.asKnown().getOrNull()?.validity() ?: 0) + + (modelSpend.asKnown().getOrNull()?.validity() ?: 0) + + (models.asKnown().getOrNull()?.size ?: 0) + + (objectPermission.asKnown().getOrNull()?.validity() ?: 0) + + (if (objectPermissionId.asKnown().isPresent) 1 else 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (permissions.asKnown().getOrNull()?.validity() ?: 0) + + (if (rotationCount.asKnown().isPresent) 1 else 0) + + (if (rotationInterval.asKnown().isPresent) 1 else 0) + + (routerSettings.asKnown().getOrNull()?.validity() ?: 0) + + (if (rpmLimit.asKnown().isPresent) 1 else 0) + + (if (softBudgetCooldown.asKnown().isPresent) 1 else 0) + + (if (spend.asKnown().isPresent) 1 else 0) + + (if (teamId.asKnown().isPresent) 1 else 0) + + (if (tpmLimit.asKnown().isPresent) 1 else 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + (if (updatedBy.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + class Aliases + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Aliases]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Aliases]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aliases: Aliases) = apply { + additionalProperties = aliases.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Aliases]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Aliases = Aliases(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Aliases = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Aliases && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Aliases{additionalProperties=$additionalProperties}" + } + + class Config + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Config]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Config]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(config: Config) = apply { + additionalProperties = config.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Config]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Config = Config(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Config = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Config && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Config{additionalProperties=$additionalProperties}" + } + @JsonDeserialize(using = Expires.Deserializer::class) @JsonSerialize(using = Expires.Serializer::class) class Expires @@ -1074,13 +1896,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) offsetDateTime != null -> visitor.visitOffsetDateTime(offsetDateTime) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -1099,15 +1920,43 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitOffsetDateTime(offsetDateTime: OffsetDateTime) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Expires && string == other.string && offsetDateTime == other.offsetDateTime /* spotless:on */ + return other is Expires && + string == other.string && + offsetDateTime == other.offsetDateTime } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, offsetDateTime) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(string, offsetDateTime) override fun toString(): String = when { @@ -1155,14 +2004,28 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Expires { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return Expires(string = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Expires(offsetDateTime = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Expires(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> Expires(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() } - tryDeserialize(node, jacksonTypeRef())?.let { - return Expires(offsetDateTime = it, _json = json) - } - - return Expires(_json = json) } } @@ -1183,20 +2046,1311 @@ private constructor( } } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + class LitellmBudgetTable + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [LitellmBudgetTable]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LitellmBudgetTable]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(litellmBudgetTable: LitellmBudgetTable) = apply { + additionalProperties = litellmBudgetTable.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [LitellmBudgetTable]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): LitellmBudgetTable = LitellmBudgetTable(additionalProperties.toImmutable()) } - return /* spotless:off */ other is KeyBlockResponse && token == other.token && aliases == other.aliases && allowedCacheControls == other.allowedCacheControls && blocked == other.blocked && budgetDuration == other.budgetDuration && budgetResetAt == other.budgetResetAt && config == other.config && createdAt == other.createdAt && createdBy == other.createdBy && expires == other.expires && keyAlias == other.keyAlias && keyName == other.keyName && llmBudgetTable == other.llmBudgetTable && maxBudget == other.maxBudget && maxParallelRequests == other.maxParallelRequests && metadata == other.metadata && modelMaxBudget == other.modelMaxBudget && modelSpend == other.modelSpend && models == other.models && orgId == other.orgId && permissions == other.permissions && rpmLimit == other.rpmLimit && softBudgetCooldown == other.softBudgetCooldown && spend == other.spend && teamId == other.teamId && tpmLimit == other.tpmLimit && updatedAt == other.updatedAt && updatedBy == other.updatedBy && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ + private var validated: Boolean = false + + fun validate(): LitellmBudgetTable = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is LitellmBudgetTable && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "LitellmBudgetTable{additionalProperties=$additionalProperties}" } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(token, aliases, allowedCacheControls, blocked, budgetDuration, budgetResetAt, config, createdAt, createdBy, expires, keyAlias, keyName, llmBudgetTable, maxBudget, maxParallelRequests, metadata, modelMaxBudget, modelSpend, models, orgId, permissions, rpmLimit, softBudgetCooldown, spend, teamId, tpmLimit, updatedAt, updatedBy, userId, additionalProperties) } - /* spotless:on */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + class ModelMaxBudget + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelMaxBudget]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelMaxBudget]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelMaxBudget: ModelMaxBudget) = apply { + additionalProperties = modelMaxBudget.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelMaxBudget]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelMaxBudget = ModelMaxBudget(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelMaxBudget = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelMaxBudget && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelMaxBudget{additionalProperties=$additionalProperties}" + } + + class ModelSpend + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelSpend]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelSpend]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelSpend: ModelSpend) = apply { + additionalProperties = modelSpend.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelSpend]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelSpend = ModelSpend(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelSpend = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelSpend && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelSpend{additionalProperties=$additionalProperties}" + } + + /** Represents a LiteLLM_ObjectPermissionTable record */ + class ObjectPermission + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val objectPermissionId: JsonField, + private val agentAccessGroups: JsonField>, + private val agents: JsonField>, + private val mcpAccessGroups: JsonField>, + private val mcpServers: JsonField>, + private val mcpToolPermissions: JsonField, + private val vectorStores: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("object_permission_id") + @ExcludeMissing + objectPermissionId: JsonField = JsonMissing.of(), + @JsonProperty("agent_access_groups") + @ExcludeMissing + agentAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("agents") + @ExcludeMissing + agents: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_access_groups") + @ExcludeMissing + mcpAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_servers") + @ExcludeMissing + mcpServers: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + mcpToolPermissions: JsonField = JsonMissing.of(), + @JsonProperty("vector_stores") + @ExcludeMissing + vectorStores: JsonField> = JsonMissing.of(), + ) : this( + objectPermissionId, + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun objectPermissionId(): String = objectPermissionId.getRequired("object_permission_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun agentAccessGroups(): Optional> = + agentAccessGroups.getOptional("agent_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun agents(): Optional> = agents.getOptional("agents") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpAccessGroups(): Optional> = + mcpAccessGroups.getOptional("mcp_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpServers(): Optional> = mcpServers.getOptional("mcp_servers") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpToolPermissions(): Optional = + mcpToolPermissions.getOptional("mcp_tool_permissions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun vectorStores(): Optional> = vectorStores.getOptional("vector_stores") + + /** + * Returns the raw JSON value of [objectPermissionId]. + * + * Unlike [objectPermissionId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("object_permission_id") + @ExcludeMissing + fun _objectPermissionId(): JsonField = objectPermissionId + + /** + * Returns the raw JSON value of [agentAccessGroups]. + * + * Unlike [agentAccessGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("agent_access_groups") + @ExcludeMissing + fun _agentAccessGroups(): JsonField> = agentAccessGroups + + /** + * Returns the raw JSON value of [agents]. + * + * Unlike [agents], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("agents") @ExcludeMissing fun _agents(): JsonField> = agents + + /** + * Returns the raw JSON value of [mcpAccessGroups]. + * + * Unlike [mcpAccessGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("mcp_access_groups") + @ExcludeMissing + fun _mcpAccessGroups(): JsonField> = mcpAccessGroups + + /** + * Returns the raw JSON value of [mcpServers]. + * + * Unlike [mcpServers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("mcp_servers") + @ExcludeMissing + fun _mcpServers(): JsonField> = mcpServers + + /** + * Returns the raw JSON value of [mcpToolPermissions]. + * + * Unlike [mcpToolPermissions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + fun _mcpToolPermissions(): JsonField = mcpToolPermissions + + /** + * Returns the raw JSON value of [vectorStores]. + * + * Unlike [vectorStores], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("vector_stores") + @ExcludeMissing + fun _vectorStores(): JsonField> = vectorStores + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ObjectPermission]. + * + * The following fields are required: + * ```java + * .objectPermissionId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ObjectPermission]. */ + class Builder internal constructor() { + + private var objectPermissionId: JsonField? = null + private var agentAccessGroups: JsonField>? = null + private var agents: JsonField>? = null + private var mcpAccessGroups: JsonField>? = null + private var mcpServers: JsonField>? = null + private var mcpToolPermissions: JsonField = JsonMissing.of() + private var vectorStores: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(objectPermission: ObjectPermission) = apply { + objectPermissionId = objectPermission.objectPermissionId + agentAccessGroups = objectPermission.agentAccessGroups.map { it.toMutableList() } + agents = objectPermission.agents.map { it.toMutableList() } + mcpAccessGroups = objectPermission.mcpAccessGroups.map { it.toMutableList() } + mcpServers = objectPermission.mcpServers.map { it.toMutableList() } + mcpToolPermissions = objectPermission.mcpToolPermissions + vectorStores = objectPermission.vectorStores.map { it.toMutableList() } + additionalProperties = objectPermission.additionalProperties.toMutableMap() + } + + fun objectPermissionId(objectPermissionId: String) = + objectPermissionId(JsonField.of(objectPermissionId)) + + /** + * Sets [Builder.objectPermissionId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermissionId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun objectPermissionId(objectPermissionId: JsonField) = apply { + this.objectPermissionId = objectPermissionId + } + + fun agentAccessGroups(agentAccessGroups: List?) = + agentAccessGroups(JsonField.ofNullable(agentAccessGroups)) + + /** + * Alias for calling [Builder.agentAccessGroups] with `agentAccessGroups.orElse(null)`. + */ + fun agentAccessGroups(agentAccessGroups: Optional>) = + agentAccessGroups(agentAccessGroups.getOrNull()) + + /** + * Sets [Builder.agentAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.agentAccessGroups] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun agentAccessGroups(agentAccessGroups: JsonField>) = apply { + this.agentAccessGroups = agentAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agentAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgentAccessGroup(agentAccessGroup: String) = apply { + agentAccessGroups = + (agentAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("agentAccessGroups", it).add(agentAccessGroup) + } + } + + fun agents(agents: List?) = agents(JsonField.ofNullable(agents)) + + /** Alias for calling [Builder.agents] with `agents.orElse(null)`. */ + fun agents(agents: Optional>) = agents(agents.getOrNull()) + + /** + * Sets [Builder.agents] to an arbitrary JSON value. + * + * You should usually call [Builder.agents] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun agents(agents: JsonField>) = apply { + this.agents = agents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgent(agent: String) = apply { + agents = + (agents ?: JsonField.of(mutableListOf())).also { + checkKnown("agents", it).add(agent) + } + } + + fun mcpAccessGroups(mcpAccessGroups: List?) = + mcpAccessGroups(JsonField.ofNullable(mcpAccessGroups)) + + /** Alias for calling [Builder.mcpAccessGroups] with `mcpAccessGroups.orElse(null)`. */ + fun mcpAccessGroups(mcpAccessGroups: Optional>) = + mcpAccessGroups(mcpAccessGroups.getOrNull()) + + /** + * Sets [Builder.mcpAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpAccessGroups] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun mcpAccessGroups(mcpAccessGroups: JsonField>) = apply { + this.mcpAccessGroups = mcpAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpAccessGroup(mcpAccessGroup: String) = apply { + mcpAccessGroups = + (mcpAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpAccessGroups", it).add(mcpAccessGroup) + } + } + + fun mcpServers(mcpServers: List?) = mcpServers(JsonField.ofNullable(mcpServers)) + + /** Alias for calling [Builder.mcpServers] with `mcpServers.orElse(null)`. */ + fun mcpServers(mcpServers: Optional>) = mcpServers(mcpServers.getOrNull()) + + /** + * Sets [Builder.mcpServers] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpServers] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun mcpServers(mcpServers: JsonField>) = apply { + this.mcpServers = mcpServers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpServers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpServer(mcpServer: String) = apply { + mcpServers = + (mcpServers ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpServers", it).add(mcpServer) + } + } + + fun mcpToolPermissions(mcpToolPermissions: McpToolPermissions?) = + mcpToolPermissions(JsonField.ofNullable(mcpToolPermissions)) + + /** + * Alias for calling [Builder.mcpToolPermissions] with + * `mcpToolPermissions.orElse(null)`. + */ + fun mcpToolPermissions(mcpToolPermissions: Optional) = + mcpToolPermissions(mcpToolPermissions.getOrNull()) + + /** + * Sets [Builder.mcpToolPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpToolPermissions] with a well-typed + * [McpToolPermissions] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun mcpToolPermissions(mcpToolPermissions: JsonField) = apply { + this.mcpToolPermissions = mcpToolPermissions + } + + fun vectorStores(vectorStores: List?) = + vectorStores(JsonField.ofNullable(vectorStores)) + + /** Alias for calling [Builder.vectorStores] with `vectorStores.orElse(null)`. */ + fun vectorStores(vectorStores: Optional>) = + vectorStores(vectorStores.getOrNull()) + + /** + * Sets [Builder.vectorStores] to an arbitrary JSON value. + * + * You should usually call [Builder.vectorStores] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun vectorStores(vectorStores: JsonField>) = apply { + this.vectorStores = vectorStores.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [vectorStores]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addVectorStore(vectorStore: String) = apply { + vectorStores = + (vectorStores ?: JsonField.of(mutableListOf())).also { + checkKnown("vectorStores", it).add(vectorStore) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ObjectPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objectPermissionId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ObjectPermission = + ObjectPermission( + checkRequired("objectPermissionId", objectPermissionId), + (agentAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (agents ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpServers ?: JsonMissing.of()).map { it.toImmutable() }, + mcpToolPermissions, + (vectorStores ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ObjectPermission = apply { + if (validated) { + return@apply + } + + objectPermissionId() + agentAccessGroups() + agents() + mcpAccessGroups() + mcpServers() + mcpToolPermissions().ifPresent { it.validate() } + vectorStores() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (objectPermissionId.asKnown().isPresent) 1 else 0) + + (agentAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (agents.asKnown().getOrNull()?.size ?: 0) + + (mcpAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (mcpServers.asKnown().getOrNull()?.size ?: 0) + + (mcpToolPermissions.asKnown().getOrNull()?.validity() ?: 0) + + (vectorStores.asKnown().getOrNull()?.size ?: 0) + + class McpToolPermissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [McpToolPermissions]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [McpToolPermissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(mcpToolPermissions: McpToolPermissions) = apply { + additionalProperties = mcpToolPermissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [McpToolPermissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): McpToolPermissions = + McpToolPermissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): McpToolPermissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is McpToolPermissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "McpToolPermissions{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ObjectPermission && + objectPermissionId == other.objectPermissionId && + agentAccessGroups == other.agentAccessGroups && + agents == other.agents && + mcpAccessGroups == other.mcpAccessGroups && + mcpServers == other.mcpServers && + mcpToolPermissions == other.mcpToolPermissions && + vectorStores == other.vectorStores && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + objectPermissionId, + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ObjectPermission{objectPermissionId=$objectPermissionId, agentAccessGroups=$agentAccessGroups, agents=$agents, mcpAccessGroups=$mcpAccessGroups, mcpServers=$mcpServers, mcpToolPermissions=$mcpToolPermissions, vectorStores=$vectorStores, additionalProperties=$additionalProperties}" + } + + class Permissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Permissions]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Permissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(permissions: Permissions) = apply { + additionalProperties = permissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Permissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Permissions = Permissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Permissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Permissions && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Permissions{additionalProperties=$additionalProperties}" + } + + class RouterSettings + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RouterSettings]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RouterSettings]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(routerSettings: RouterSettings) = apply { + additionalProperties = routerSettings.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RouterSettings]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RouterSettings = RouterSettings(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): RouterSettings = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RouterSettings && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "RouterSettings{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is KeyBlockResponse && + token == other.token && + aliases == other.aliases && + allowedCacheControls == other.allowedCacheControls && + allowedRoutes == other.allowedRoutes && + autoRotate == other.autoRotate && + blocked == other.blocked && + budgetDuration == other.budgetDuration && + budgetResetAt == other.budgetResetAt && + config == other.config && + createdAt == other.createdAt && + createdBy == other.createdBy && + expires == other.expires && + keyAlias == other.keyAlias && + keyName == other.keyName && + keyRotationAt == other.keyRotationAt && + lastRotationAt == other.lastRotationAt && + litellmBudgetTable == other.litellmBudgetTable && + maxBudget == other.maxBudget && + maxParallelRequests == other.maxParallelRequests && + metadata == other.metadata && + modelMaxBudget == other.modelMaxBudget && + modelSpend == other.modelSpend && + models == other.models && + objectPermission == other.objectPermission && + objectPermissionId == other.objectPermissionId && + orgId == other.orgId && + permissions == other.permissions && + rotationCount == other.rotationCount && + rotationInterval == other.rotationInterval && + routerSettings == other.routerSettings && + rpmLimit == other.rpmLimit && + softBudgetCooldown == other.softBudgetCooldown && + spend == other.spend && + teamId == other.teamId && + tpmLimit == other.tpmLimit && + updatedAt == other.updatedAt && + updatedBy == other.updatedBy && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + token, + aliases, + allowedCacheControls, + allowedRoutes, + autoRotate, + blocked, + budgetDuration, + budgetResetAt, + config, + createdAt, + createdBy, + expires, + keyAlias, + keyName, + keyRotationAt, + lastRotationAt, + litellmBudgetTable, + maxBudget, + maxParallelRequests, + metadata, + modelMaxBudget, + modelSpend, + models, + objectPermission, + objectPermissionId, + orgId, + permissions, + rotationCount, + rotationInterval, + routerSettings, + rpmLimit, + softBudgetCooldown, + spend, + teamId, + tpmLimit, + updatedAt, + updatedBy, + userId, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "KeyBlockResponse{token=$token, aliases=$aliases, allowedCacheControls=$allowedCacheControls, blocked=$blocked, budgetDuration=$budgetDuration, budgetResetAt=$budgetResetAt, config=$config, createdAt=$createdAt, createdBy=$createdBy, expires=$expires, keyAlias=$keyAlias, keyName=$keyName, llmBudgetTable=$llmBudgetTable, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelSpend=$modelSpend, models=$models, orgId=$orgId, permissions=$permissions, rpmLimit=$rpmLimit, softBudgetCooldown=$softBudgetCooldown, spend=$spend, teamId=$teamId, tpmLimit=$tpmLimit, updatedAt=$updatedAt, updatedBy=$updatedBy, userId=$userId, additionalProperties=$additionalProperties}" + "KeyBlockResponse{token=$token, aliases=$aliases, allowedCacheControls=$allowedCacheControls, allowedRoutes=$allowedRoutes, autoRotate=$autoRotate, blocked=$blocked, budgetDuration=$budgetDuration, budgetResetAt=$budgetResetAt, config=$config, createdAt=$createdAt, createdBy=$createdBy, expires=$expires, keyAlias=$keyAlias, keyName=$keyName, keyRotationAt=$keyRotationAt, lastRotationAt=$lastRotationAt, litellmBudgetTable=$litellmBudgetTable, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelSpend=$modelSpend, models=$models, objectPermission=$objectPermission, objectPermissionId=$objectPermissionId, orgId=$orgId, permissions=$permissions, rotationCount=$rotationCount, rotationInterval=$rotationInterval, routerSettings=$routerSettings, rpmLimit=$rpmLimit, softBudgetCooldown=$softBudgetCooldown, spend=$spend, teamId=$teamId, tpmLimit=$tpmLimit, updatedAt=$updatedAt, updatedBy=$updatedBy, userId=$userId, additionalProperties=$additionalProperties}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyCheckHealthParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyCheckHealthParams.kt index c5cd162b..d6049fb8 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyCheckHealthParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyCheckHealthParams.kt @@ -29,7 +29,9 @@ import java.util.Optional * { * "key": "healthy", * "logging_callbacks": { - * "callbacks": ["gcs_bucket"], + * "callbacks": [ + * "gcs_bucket" + * ], * "status": "healthy", * "details": "No logger exceptions triggered, system is healthy. Manually check if logs were sent to ['gcs_bucket']" * } @@ -41,7 +43,9 @@ import java.util.Optional * { * "key": "unhealthy", * "logging_callbacks": { - * "callbacks": ["gcs_bucket"], + * "callbacks": [ + * "gcs_bucket" + * ], * "status": "unhealthy", * "details": "Logger exceptions triggered, system is unhealthy: Failed to load vertex credentials. Check to see if credentials containing partial/invalid information." * } @@ -55,10 +59,13 @@ private constructor( private val additionalBodyProperties: Map, ) : Params { + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -218,8 +225,7 @@ private constructor( ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) override fun _headers(): Headers = additionalHeaders @@ -231,10 +237,14 @@ private constructor( return true } - return /* spotless:off */ other is KeyCheckHealthParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is KeyCheckHealthParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "KeyCheckHealthParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyCheckHealthResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyCheckHealthResponse.kt index 2528c31f..16f0b3d5 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyCheckHealthResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyCheckHealthResponse.kt @@ -20,6 +20,7 @@ import java.util.Optional import kotlin.jvm.optionals.getOrNull class KeyCheckHealthResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val key: JsonField, private val loggingCallbacks: JsonField, @@ -38,14 +39,14 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun key(): Optional = Optional.ofNullable(key.getNullable("key")) + fun key(): Optional = key.getOptional("key") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun loggingCallbacks(): Optional = - Optional.ofNullable(loggingCallbacks.getNullable("logging_callbacks")) + loggingCallbacks.getOptional("logging_callbacks") /** * Returns the raw JSON value of [key]. @@ -159,11 +160,29 @@ private constructor( return@apply } - key() + key().ifPresent { it.validate() } loggingCallbacks().ifPresent { it.validate() } validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (key.asKnown().getOrNull()?.validity() ?: 0) + + (loggingCallbacks.asKnown().getOrNull()?.validity() ?: 0) + class Key @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -248,12 +267,39 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Key = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Key && value == other.value /* spotless:on */ + return other is Key && value == other.value } override fun hashCode() = value.hashCode() @@ -262,6 +308,7 @@ private constructor( } class LoggingCallbacks + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val callbacks: JsonField>, private val details: JsonField, @@ -282,20 +329,19 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun callbacks(): Optional> = - Optional.ofNullable(callbacks.getNullable("callbacks")) + fun callbacks(): Optional> = callbacks.getOptional("callbacks") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun details(): Optional = Optional.ofNullable(details.getNullable("details")) + fun details(): Optional = details.getOptional("details") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun status(): Optional = Optional.ofNullable(status.getNullable("status")) + fun status(): Optional = status.getOptional("status") /** * Returns the raw JSON value of [callbacks]. @@ -446,10 +492,30 @@ private constructor( callbacks() details() - status() + status().ifPresent { it.validate() } validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (callbacks.asKnown().getOrNull()?.size ?: 0) + + (if (details.asKnown().isPresent) 1 else 0) + + (status.asKnown().getOrNull()?.validity() ?: 0) + class Status @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -539,12 +605,39 @@ private constructor( HanzoInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Status = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Status && value == other.value /* spotless:on */ + return other is Status && value == other.value } override fun hashCode() = value.hashCode() @@ -557,12 +650,16 @@ private constructor( return true } - return /* spotless:off */ other is LoggingCallbacks && callbacks == other.callbacks && details == other.details && status == other.status && additionalProperties == other.additionalProperties /* spotless:on */ + return other is LoggingCallbacks && + callbacks == other.callbacks && + details == other.details && + status == other.status && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(callbacks, details, status, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash(callbacks, details, status, additionalProperties) + } override fun hashCode(): Int = hashCode @@ -575,12 +672,13 @@ private constructor( return true } - return /* spotless:off */ other is KeyCheckHealthResponse && key == other.key && loggingCallbacks == other.loggingCallbacks && additionalProperties == other.additionalProperties /* spotless:on */ + return other is KeyCheckHealthResponse && + key == other.key && + loggingCallbacks == other.loggingCallbacks && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(key, loggingCallbacks, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyDeleteParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyDeleteParams.kt index c78007c0..71dcc893 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyDeleteParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyDeleteParams.kt @@ -45,17 +45,17 @@ import kotlin.jvm.optionals.getOrNull */ class KeyDeleteParams private constructor( - private val llmChangedBy: String?, + private val litellmChangedBy: String?, private val body: Body, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { /** - * The llm-changed-by header enables tracking of actions performed by authorized users on behalf - * of other users, providing an audit trail for accountability + * The litellm-changed-by header enables tracking of actions performed by authorized users on + * behalf of other users, providing an audit trail for accountability */ - fun llmChangedBy(): Optional = Optional.ofNullable(llmChangedBy) + fun litellmChangedBy(): Optional = Optional.ofNullable(litellmChangedBy) /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -85,8 +85,10 @@ private constructor( fun _additionalBodyProperties(): Map = body._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -102,27 +104,40 @@ private constructor( /** A builder for [KeyDeleteParams]. */ class Builder internal constructor() { - private var llmChangedBy: String? = null + private var litellmChangedBy: String? = null private var body: Body.Builder = Body.builder() private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(keyDeleteParams: KeyDeleteParams) = apply { - llmChangedBy = keyDeleteParams.llmChangedBy + litellmChangedBy = keyDeleteParams.litellmChangedBy body = keyDeleteParams.body.toBuilder() additionalHeaders = keyDeleteParams.additionalHeaders.toBuilder() additionalQueryParams = keyDeleteParams.additionalQueryParams.toBuilder() } /** - * The llm-changed-by header enables tracking of actions performed by authorized users on - * behalf of other users, providing an audit trail for accountability + * The litellm-changed-by header enables tracking of actions performed by authorized users + * on behalf of other users, providing an audit trail for accountability */ - fun llmChangedBy(llmChangedBy: String?) = apply { this.llmChangedBy = llmChangedBy } + fun litellmChangedBy(litellmChangedBy: String?) = apply { + this.litellmChangedBy = litellmChangedBy + } + + /** Alias for calling [Builder.litellmChangedBy] with `litellmChangedBy.orElse(null)`. */ + fun litellmChangedBy(litellmChangedBy: Optional) = + litellmChangedBy(litellmChangedBy.getOrNull()) - /** Alias for calling [Builder.llmChangedBy] with `llmChangedBy.orElse(null)`. */ - fun llmChangedBy(llmChangedBy: Optional) = llmChangedBy(llmChangedBy.getOrNull()) + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [keyAliases] + * - [keys] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } fun keyAliases(keyAliases: List?) = apply { body.keyAliases(keyAliases) } @@ -290,19 +305,19 @@ private constructor( */ fun build(): KeyDeleteParams = KeyDeleteParams( - llmChangedBy, + litellmChangedBy, body.build(), additionalHeaders.build(), additionalQueryParams.build(), ) } - @JvmSynthetic internal fun _body(): Body = body + fun _body(): Body = body override fun _headers(): Headers = Headers.builder() .apply { - llmChangedBy?.let { put("llm-changed-by", it) } + litellmChangedBy?.let { put("litellm-changed-by", it) } putAll(additionalHeaders) } .build() @@ -310,6 +325,7 @@ private constructor( override fun _queryParams(): QueryParams = additionalQueryParams class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val keyAliases: JsonField>, private val keys: JsonField>, @@ -328,14 +344,13 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun keyAliases(): Optional> = - Optional.ofNullable(keyAliases.getNullable("key_aliases")) + fun keyAliases(): Optional> = keyAliases.getOptional("key_aliases") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun keys(): Optional> = Optional.ofNullable(keys.getNullable("keys")) + fun keys(): Optional> = keys.getOptional("keys") /** * Returns the raw JSON value of [keyAliases]. @@ -483,17 +498,36 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (keyAliases.asKnown().getOrNull()?.size ?: 0) + (keys.asKnown().getOrNull()?.size ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && keyAliases == other.keyAliases && keys == other.keys && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Body && + keyAliases == other.keyAliases && + keys == other.keys && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(keyAliases, keys, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -506,11 +540,16 @@ private constructor( return true } - return /* spotless:off */ other is KeyDeleteParams && llmChangedBy == other.llmChangedBy && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is KeyDeleteParams && + litellmChangedBy == other.litellmChangedBy && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(llmChangedBy, body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(litellmChangedBy, body, additionalHeaders, additionalQueryParams) override fun toString() = - "KeyDeleteParams{llmChangedBy=$llmChangedBy, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "KeyDeleteParams{litellmChangedBy=$litellmChangedBy, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyDeleteResponse.kt index 32548cac..76abac82 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.key import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class KeyDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap x. * - metadata: Optional[dict] - Metadata for key, store information for key. Example metadata = - * {"team": "core-infra", "app": "app2", "email": "z@hanzo.ai" } + * {"team": "core-infra", "app": "app2", "email": "ishaan@berri.ai" } * - guardrails: Optional[List[str]] - List of active guardrails for the key + * - disable_global_guardrails: Optional[bool] - Whether to disable global guardrails for the key. * - permissions: Optional[dict] - key-specific permissions. Currently just used for turning off pii * masking (if connected). Example - {"pii": false} * - model_max_budget: Optional[Dict[str, BudgetConfig]] - Model-specific budgets {"gpt-4": @@ -62,19 +67,56 @@ import kotlin.jvm.optionals.getOrNull * 1000, "gpt-3.5-turbo": 1000}. IF null or {} then no model specific rpm limit. * - model_tpm_limit: Optional[dict] - key-specific model tpm limit. Example - {"text-davinci-002": * 1000, "gpt-3.5-turbo": 1000}. IF null or {} then no model specific tpm limit. + * - tpm_limit_type: Optional[str] - Type of tpm limit. Options: "best_effort_throughput" (no error + * if we're overallocating tpm), "guaranteed_throughput" (raise an error if we're overallocating + * tpm), "dynamic" (dynamically exceed limit when no 429 errors). Defaults to + * "best_effort_throughput". + * - rpm_limit_type: Optional[str] - Type of rpm limit. Options: "best_effort_throughput" (no error + * if we're overallocating rpm), "guaranteed_throughput" (raise an error if we're overallocating + * rpm), "dynamic" (dynamically exceed limit when no 429 errors). Defaults to + * "best_effort_throughput". * - allowed_cache_controls: Optional[list] - List of allowed cache control values. * Example - ["no-cache", "no-store"]. See all values - - * https://docs.hanzo.ai/docs/proxy/caching#turn-on--off-caching-per-request + * https://docs.litellm.ai/docs/proxy/caching#turn-on--off-caching-per-request * - blocked: Optional[bool] - Whether the key is blocked. * - rpm_limit: Optional[int] - Specify rpm limit for a given key (Requests per minute) * - tpm_limit: Optional[int] - Specify tpm limit for a given key (Tokens per minute) * - soft_budget: Optional[float] - Specify soft budget for a given key. Will trigger a slack alert * when this soft budget is reached. * - tags: Optional[List[str]] - Tags for - * [tracking spend](https://llm.vercel.app/docs/proxy/enterprise#tracking-spend-for-custom-tags) - * and/or doing [tag-based routing](https://llm.vercel.app/docs/proxy/tag_routing). + * [tracking spend](https://litellm.vercel.app/docs/proxy/enterprise#tracking-spend-for-custom-tags) + * and/or doing [tag-based routing](https://litellm.vercel.app/docs/proxy/tag_routing). + * - prompts: Optional[List[str]] - List of prompts that the key is allowed to use. * - enforced_params: Optional[List[str]] - List of enforced params for the key (Enterprise only). - * [Docs](https://docs.hanzo.ai/docs/proxy/enterprise#enforce-required-params-for-llm-requests) + * [Docs](https://docs.litellm.ai/docs/proxy/enterprise#enforce-required-params-for-llm-requests) + * - prompts: Optional[List[str]] - List of prompts that the key is allowed to use. + * - allowed_routes: Optional[list] - List of allowed routes for the key. Store the actual route or + * store a wildcard pattern for a set of routes. + * Example - ["/chat/completions", "/embeddings", "/keys/*"] + * - allowed_passthrough_routes: Optional[list] - List of allowed pass through endpoints for the + * key. Store the actual endpoint or store a wildcard pattern for a set of endpoints. + * Example - ["/my-custom-endpoint"]. Use this instead of allowed_routes, if you just want to + * specify which pass through endpoints the key can access, without specifying the routes. If + * allowed_routes is specified, allowed_pass_through_endpoints is ignored. + * - object_permission: Optional[LiteLLM_ObjectPermissionBase] - key-specific object permission. + * Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": + * ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object + * permission. + * - key_type: Optional[str] - Type of key that determines default allowed routes. Options: + * "llm_api" (can call LLM API routes), "management" (can call management routes), "read_only" + * (can only call info/read routes), "default" (uses default allowed routes). Defaults to + * "default". + * - prompts: Optional[List[str]] - List of allowed prompts for the key. If specified, the key will + * only be able to use these specific prompts. + * - auto_rotate: Optional[bool] - Whether this key should be automatically rotated (regenerated) + * - rotation_interval: Optional[str] - How often to auto-rotate this key (e.g., '30s', '30m', + * '30h', '30d'). Required if auto_rotate=True. + * - allowed_vector_store_indexes: Optional[List[dict]] - List of allowed vector store indexes for + * the key. Example - [{"index_name": "my-index", "index_permissions": ["write", "read"]}]. If + * specified, the key will only be able to use these specific vector store indexes. Create index, + * using `/v1/indexes` endpoint. + * - router_settings: Optional[UpdateRouterConfig] - key-specific router settings. Example - + * {"model_group_retry_policy": {"max_retries": 5}}. IF null or {} then no router settings. * * Examples: * 1. Allow users to turn on/off pii masking @@ -92,19 +134,23 @@ import kotlin.jvm.optionals.getOrNull */ class KeyGenerateParams private constructor( - private val llmChangedBy: String?, + private val litellmChangedBy: String?, private val body: Body, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { /** - * The llm-changed-by header enables tracking of actions performed by authorized users on behalf - * of other users, providing an audit trail for accountability + * The litellm-changed-by header enables tracking of actions performed by authorized users on + * behalf of other users, providing an audit trail for accountability */ - fun llmChangedBy(): Optional = Optional.ofNullable(llmChangedBy) + fun litellmChangedBy(): Optional = Optional.ofNullable(litellmChangedBy) - fun _aliases(): JsonValue = body._aliases() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aliases(): Optional = body.aliases() /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -112,6 +158,33 @@ private constructor( */ fun allowedCacheControls(): Optional> = body.allowedCacheControls() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedPassthroughRoutes(): Optional> = body.allowedPassthroughRoutes() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedRoutes(): Optional> = body.allowedRoutes() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedVectorStoreIndexes(): Optional> = + body.allowedVectorStoreIndexes() + + /** + * Whether this key should be automatically rotated + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun autoRotate(): Optional = body.autoRotate() + /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). @@ -130,7 +203,11 @@ private constructor( */ fun budgetId(): Optional = body.budgetId() - fun _config(): JsonValue = body._config() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun config(): Optional = body.config() /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -162,6 +239,14 @@ private constructor( */ fun keyAlias(): Optional = body.keyAlias() + /** + * Enum for key types that determine what routes a key can access + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun keyType(): Optional = body.keyType() + /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). @@ -174,13 +259,29 @@ private constructor( */ fun maxParallelRequests(): Optional = body.maxParallelRequests() - fun _metadata(): JsonValue = body._metadata() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = body.metadata() - fun _modelMaxBudget(): JsonValue = body._modelMaxBudget() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelMaxBudget(): Optional = body.modelMaxBudget() - fun _modelRpmLimit(): JsonValue = body._modelRpmLimit() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelRpmLimit(): Optional = body.modelRpmLimit() - fun _modelTpmLimit(): JsonValue = body._modelTpmLimit() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelTpmLimit(): Optional = body.modelTpmLimit() /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -188,7 +289,45 @@ private constructor( */ fun models(): Optional> = body.models() - fun _permissions(): JsonValue = body._permissions() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun objectPermission(): Optional = body.objectPermission() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun organizationId(): Optional = body.organizationId() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun permissions(): Optional = body.permissions() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun prompts(): Optional> = body.prompts() + + /** + * How often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rotationInterval(): Optional = body.rotationInterval() + + /** + * Set of params that you can modify via `router.update_settings()`. + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routerSettings(): Optional = body.routerSettings() /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -196,6 +335,12 @@ private constructor( */ fun rpmLimit(): Optional = body.rpmLimit() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rpmLimitType(): Optional = body.rpmLimitType() + /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). @@ -232,12 +377,25 @@ private constructor( */ fun tpmLimit(): Optional = body.tpmLimit() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tpmLimitType(): Optional = body.tpmLimitType() + /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun userId(): Optional = body.userId() + /** + * Returns the raw JSON value of [aliases]. + * + * Unlike [aliases], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _aliases(): JsonField = body._aliases() + /** * Returns the raw JSON value of [allowedCacheControls]. * @@ -246,6 +404,37 @@ private constructor( */ fun _allowedCacheControls(): JsonField> = body._allowedCacheControls() + /** + * Returns the raw JSON value of [allowedPassthroughRoutes]. + * + * Unlike [allowedPassthroughRoutes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + fun _allowedPassthroughRoutes(): JsonField> = body._allowedPassthroughRoutes() + + /** + * Returns the raw JSON value of [allowedRoutes]. + * + * Unlike [allowedRoutes], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _allowedRoutes(): JsonField> = body._allowedRoutes() + + /** + * Returns the raw JSON value of [allowedVectorStoreIndexes]. + * + * Unlike [allowedVectorStoreIndexes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + fun _allowedVectorStoreIndexes(): JsonField> = + body._allowedVectorStoreIndexes() + + /** + * Returns the raw JSON value of [autoRotate]. + * + * Unlike [autoRotate], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _autoRotate(): JsonField = body._autoRotate() + /** * Returns the raw JSON value of [blocked]. * @@ -267,6 +456,13 @@ private constructor( */ fun _budgetId(): JsonField = body._budgetId() + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _config(): JsonField = body._config() + /** * Returns the raw JSON value of [duration]. * @@ -302,6 +498,13 @@ private constructor( */ fun _keyAlias(): JsonField = body._keyAlias() + /** + * Returns the raw JSON value of [keyType]. + * + * Unlike [keyType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _keyType(): JsonField = body._keyType() + /** * Returns the raw JSON value of [maxBudget]. * @@ -317,6 +520,34 @@ private constructor( */ fun _maxParallelRequests(): JsonField = body._maxParallelRequests() + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [modelMaxBudget]. + * + * Unlike [modelMaxBudget], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _modelMaxBudget(): JsonField = body._modelMaxBudget() + + /** + * Returns the raw JSON value of [modelRpmLimit]. + * + * Unlike [modelRpmLimit], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _modelRpmLimit(): JsonField = body._modelRpmLimit() + + /** + * Returns the raw JSON value of [modelTpmLimit]. + * + * Unlike [modelTpmLimit], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _modelTpmLimit(): JsonField = body._modelTpmLimit() + /** * Returns the raw JSON value of [models]. * @@ -324,6 +555,50 @@ private constructor( */ fun _models(): JsonField> = body._models() + /** + * Returns the raw JSON value of [objectPermission]. + * + * Unlike [objectPermission], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _objectPermission(): JsonField = body._objectPermission() + + /** + * Returns the raw JSON value of [organizationId]. + * + * Unlike [organizationId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _organizationId(): JsonField = body._organizationId() + + /** + * Returns the raw JSON value of [permissions]. + * + * Unlike [permissions], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _permissions(): JsonField = body._permissions() + + /** + * Returns the raw JSON value of [prompts]. + * + * Unlike [prompts], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _prompts(): JsonField> = body._prompts() + + /** + * Returns the raw JSON value of [rotationInterval]. + * + * Unlike [rotationInterval], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _rotationInterval(): JsonField = body._rotationInterval() + + /** + * Returns the raw JSON value of [routerSettings]. + * + * Unlike [routerSettings], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _routerSettings(): JsonField = body._routerSettings() + /** * Returns the raw JSON value of [rpmLimit]. * @@ -331,6 +606,13 @@ private constructor( */ fun _rpmLimit(): JsonField = body._rpmLimit() + /** + * Returns the raw JSON value of [rpmLimitType]. + * + * Unlike [rpmLimitType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _rpmLimitType(): JsonField = body._rpmLimitType() + /** * Returns the raw JSON value of [sendInviteEmail]. * @@ -373,6 +655,13 @@ private constructor( */ fun _tpmLimit(): JsonField = body._tpmLimit() + /** + * Returns the raw JSON value of [tpmLimitType]. + * + * Unlike [tpmLimitType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tpmLimitType(): JsonField = body._tpmLimitType() + /** * Returns the raw JSON value of [userId]. * @@ -382,8 +671,10 @@ private constructor( fun _additionalBodyProperties(): Map = body._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -399,29 +690,57 @@ private constructor( /** A builder for [KeyGenerateParams]. */ class Builder internal constructor() { - private var llmChangedBy: String? = null + private var litellmChangedBy: String? = null private var body: Body.Builder = Body.builder() private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(keyGenerateParams: KeyGenerateParams) = apply { - llmChangedBy = keyGenerateParams.llmChangedBy + litellmChangedBy = keyGenerateParams.litellmChangedBy body = keyGenerateParams.body.toBuilder() additionalHeaders = keyGenerateParams.additionalHeaders.toBuilder() additionalQueryParams = keyGenerateParams.additionalQueryParams.toBuilder() } /** - * The llm-changed-by header enables tracking of actions performed by authorized users on - * behalf of other users, providing an audit trail for accountability + * The litellm-changed-by header enables tracking of actions performed by authorized users + * on behalf of other users, providing an audit trail for accountability + */ + fun litellmChangedBy(litellmChangedBy: String?) = apply { + this.litellmChangedBy = litellmChangedBy + } + + /** Alias for calling [Builder.litellmChangedBy] with `litellmChangedBy.orElse(null)`. */ + fun litellmChangedBy(litellmChangedBy: Optional) = + litellmChangedBy(litellmChangedBy.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [aliases] + * - [allowedCacheControls] + * - [allowedPassthroughRoutes] + * - [allowedRoutes] + * - [allowedVectorStoreIndexes] + * - etc. */ - fun llmChangedBy(llmChangedBy: String?) = apply { this.llmChangedBy = llmChangedBy } + fun body(body: Body) = apply { this.body = body.toBuilder() } - /** Alias for calling [Builder.llmChangedBy] with `llmChangedBy.orElse(null)`. */ - fun llmChangedBy(llmChangedBy: Optional) = llmChangedBy(llmChangedBy.getOrNull()) + fun aliases(aliases: Aliases?) = apply { body.aliases(aliases) } - fun aliases(aliases: JsonValue) = apply { body.aliases(aliases) } + /** Alias for calling [Builder.aliases] with `aliases.orElse(null)`. */ + fun aliases(aliases: Optional) = aliases(aliases.getOrNull()) + + /** + * Sets [Builder.aliases] to an arbitrary JSON value. + * + * You should usually call [Builder.aliases] with a well-typed [Aliases] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun aliases(aliases: JsonField) = apply { body.aliases(aliases) } fun allowedCacheControls(allowedCacheControls: List?) = apply { body.allowedCacheControls(allowedCacheControls) @@ -454,6 +773,118 @@ private constructor( body.addAllowedCacheControl(allowedCacheControl) } + fun allowedPassthroughRoutes(allowedPassthroughRoutes: List?) = apply { + body.allowedPassthroughRoutes(allowedPassthroughRoutes) + } + + /** + * Alias for calling [Builder.allowedPassthroughRoutes] with + * `allowedPassthroughRoutes.orElse(null)`. + */ + fun allowedPassthroughRoutes(allowedPassthroughRoutes: Optional>) = + allowedPassthroughRoutes(allowedPassthroughRoutes.getOrNull()) + + /** + * Sets [Builder.allowedPassthroughRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedPassthroughRoutes] with a well-typed + * `List` value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun allowedPassthroughRoutes(allowedPassthroughRoutes: JsonField>) = apply { + body.allowedPassthroughRoutes(allowedPassthroughRoutes) + } + + /** + * Adds a single [JsonValue] to [allowedPassthroughRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedPassthroughRoute(allowedPassthroughRoute: JsonValue) = apply { + body.addAllowedPassthroughRoute(allowedPassthroughRoute) + } + + fun allowedRoutes(allowedRoutes: List?) = apply { + body.allowedRoutes(allowedRoutes) + } + + /** Alias for calling [Builder.allowedRoutes] with `allowedRoutes.orElse(null)`. */ + fun allowedRoutes(allowedRoutes: Optional>) = + allowedRoutes(allowedRoutes.getOrNull()) + + /** + * Sets [Builder.allowedRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedRoutes] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun allowedRoutes(allowedRoutes: JsonField>) = apply { + body.allowedRoutes(allowedRoutes) + } + + /** + * Adds a single [JsonValue] to [allowedRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedRoute(allowedRoute: JsonValue) = apply { body.addAllowedRoute(allowedRoute) } + + fun allowedVectorStoreIndexes(allowedVectorStoreIndexes: List?) = + apply { + body.allowedVectorStoreIndexes(allowedVectorStoreIndexes) + } + + /** + * Alias for calling [Builder.allowedVectorStoreIndexes] with + * `allowedVectorStoreIndexes.orElse(null)`. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: Optional> + ) = allowedVectorStoreIndexes(allowedVectorStoreIndexes.getOrNull()) + + /** + * Sets [Builder.allowedVectorStoreIndexes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedVectorStoreIndexes] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: JsonField> + ) = apply { body.allowedVectorStoreIndexes(allowedVectorStoreIndexes) } + + /** + * Adds a single [AllowedVectorStoreIndex] to [allowedVectorStoreIndexes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedVectorStoreIndex(allowedVectorStoreIndex: AllowedVectorStoreIndex) = apply { + body.addAllowedVectorStoreIndex(allowedVectorStoreIndex) + } + + /** Whether this key should be automatically rotated */ + fun autoRotate(autoRotate: Boolean?) = apply { body.autoRotate(autoRotate) } + + /** + * Alias for [Builder.autoRotate]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun autoRotate(autoRotate: Boolean) = autoRotate(autoRotate as Boolean?) + + /** Alias for calling [Builder.autoRotate] with `autoRotate.orElse(null)`. */ + fun autoRotate(autoRotate: Optional) = autoRotate(autoRotate.getOrNull()) + + /** + * Sets [Builder.autoRotate] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRotate] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun autoRotate(autoRotate: JsonField) = apply { body.autoRotate(autoRotate) } + fun blocked(blocked: Boolean?) = apply { body.blocked(blocked) } /** @@ -504,7 +935,18 @@ private constructor( */ fun budgetId(budgetId: JsonField) = apply { body.budgetId(budgetId) } - fun config(config: JsonValue) = apply { body.config(config) } + fun config(config: Config?) = apply { body.config(config) } + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [Config] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun config(config: JsonField) = apply { body.config(config) } fun duration(duration: String?) = apply { body.duration(duration) } @@ -592,6 +1034,20 @@ private constructor( */ fun keyAlias(keyAlias: JsonField) = apply { body.keyAlias(keyAlias) } + /** Enum for key types that determine what routes a key can access */ + fun keyType(keyType: KeyType?) = apply { body.keyType(keyType) } + + /** Alias for calling [Builder.keyType] with `keyType.orElse(null)`. */ + fun keyType(keyType: Optional) = keyType(keyType.getOrNull()) + + /** + * Sets [Builder.keyType] to an arbitrary JSON value. + * + * You should usually call [Builder.keyType] with a well-typed [KeyType] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun keyType(keyType: JsonField) = apply { body.keyType(keyType) } + fun maxBudget(maxBudget: Double?) = apply { body.maxBudget(maxBudget) } /** @@ -642,15 +1098,76 @@ private constructor( body.maxParallelRequests(maxParallelRequests) } - fun metadata(metadata: JsonValue) = apply { body.metadata(metadata) } + fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } - fun modelMaxBudget(modelMaxBudget: JsonValue) = apply { + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } + + fun modelMaxBudget(modelMaxBudget: ModelMaxBudget?) = apply { + body.modelMaxBudget(modelMaxBudget) + } + + /** Alias for calling [Builder.modelMaxBudget] with `modelMaxBudget.orElse(null)`. */ + fun modelMaxBudget(modelMaxBudget: Optional) = + modelMaxBudget(modelMaxBudget.getOrNull()) + + /** + * Sets [Builder.modelMaxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.modelMaxBudget] with a well-typed [ModelMaxBudget] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelMaxBudget(modelMaxBudget: JsonField) = apply { body.modelMaxBudget(modelMaxBudget) } - fun modelRpmLimit(modelRpmLimit: JsonValue) = apply { body.modelRpmLimit(modelRpmLimit) } + fun modelRpmLimit(modelRpmLimit: ModelRpmLimit?) = apply { + body.modelRpmLimit(modelRpmLimit) + } + + /** Alias for calling [Builder.modelRpmLimit] with `modelRpmLimit.orElse(null)`. */ + fun modelRpmLimit(modelRpmLimit: Optional) = + modelRpmLimit(modelRpmLimit.getOrNull()) + + /** + * Sets [Builder.modelRpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.modelRpmLimit] with a well-typed [ModelRpmLimit] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelRpmLimit(modelRpmLimit: JsonField) = apply { + body.modelRpmLimit(modelRpmLimit) + } + + fun modelTpmLimit(modelTpmLimit: ModelTpmLimit?) = apply { + body.modelTpmLimit(modelTpmLimit) + } + + /** Alias for calling [Builder.modelTpmLimit] with `modelTpmLimit.orElse(null)`. */ + fun modelTpmLimit(modelTpmLimit: Optional) = + modelTpmLimit(modelTpmLimit.getOrNull()) - fun modelTpmLimit(modelTpmLimit: JsonValue) = apply { body.modelTpmLimit(modelTpmLimit) } + /** + * Sets [Builder.modelTpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.modelTpmLimit] with a well-typed [ModelTpmLimit] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelTpmLimit(modelTpmLimit: JsonField) = apply { + body.modelTpmLimit(modelTpmLimit) + } fun models(models: List?) = apply { body.models(models) } @@ -673,7 +1190,118 @@ private constructor( */ fun addModel(model: JsonValue) = apply { body.addModel(model) } - fun permissions(permissions: JsonValue) = apply { body.permissions(permissions) } + fun objectPermission(objectPermission: ObjectPermission?) = apply { + body.objectPermission(objectPermission) + } + + /** Alias for calling [Builder.objectPermission] with `objectPermission.orElse(null)`. */ + fun objectPermission(objectPermission: Optional) = + objectPermission(objectPermission.getOrNull()) + + /** + * Sets [Builder.objectPermission] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermission] with a well-typed [ObjectPermission] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun objectPermission(objectPermission: JsonField) = apply { + body.objectPermission(objectPermission) + } + + fun organizationId(organizationId: String?) = apply { body.organizationId(organizationId) } + + /** Alias for calling [Builder.organizationId] with `organizationId.orElse(null)`. */ + fun organizationId(organizationId: Optional) = + organizationId(organizationId.getOrNull()) + + /** + * Sets [Builder.organizationId] to an arbitrary JSON value. + * + * You should usually call [Builder.organizationId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun organizationId(organizationId: JsonField) = apply { + body.organizationId(organizationId) + } + + fun permissions(permissions: Permissions?) = apply { body.permissions(permissions) } + + /** Alias for calling [Builder.permissions] with `permissions.orElse(null)`. */ + fun permissions(permissions: Optional) = permissions(permissions.getOrNull()) + + /** + * Sets [Builder.permissions] to an arbitrary JSON value. + * + * You should usually call [Builder.permissions] with a well-typed [Permissions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun permissions(permissions: JsonField) = apply { + body.permissions(permissions) + } + + fun prompts(prompts: List?) = apply { body.prompts(prompts) } + + /** Alias for calling [Builder.prompts] with `prompts.orElse(null)`. */ + fun prompts(prompts: Optional>) = prompts(prompts.getOrNull()) + + /** + * Sets [Builder.prompts] to an arbitrary JSON value. + * + * You should usually call [Builder.prompts] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun prompts(prompts: JsonField>) = apply { body.prompts(prompts) } + + /** + * Adds a single [String] to [prompts]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addPrompt(prompt: String) = apply { body.addPrompt(prompt) } + + /** How often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True */ + fun rotationInterval(rotationInterval: String?) = apply { + body.rotationInterval(rotationInterval) + } + + /** Alias for calling [Builder.rotationInterval] with `rotationInterval.orElse(null)`. */ + fun rotationInterval(rotationInterval: Optional) = + rotationInterval(rotationInterval.getOrNull()) + + /** + * Sets [Builder.rotationInterval] to an arbitrary JSON value. + * + * You should usually call [Builder.rotationInterval] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rotationInterval(rotationInterval: JsonField) = apply { + body.rotationInterval(rotationInterval) + } + + /** Set of params that you can modify via `router.update_settings()`. */ + fun routerSettings(routerSettings: RouterSettings?) = apply { + body.routerSettings(routerSettings) + } + + /** Alias for calling [Builder.routerSettings] with `routerSettings.orElse(null)`. */ + fun routerSettings(routerSettings: Optional) = + routerSettings(routerSettings.getOrNull()) + + /** + * Sets [Builder.routerSettings] to an arbitrary JSON value. + * + * You should usually call [Builder.routerSettings] with a well-typed [RouterSettings] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun routerSettings(routerSettings: JsonField) = apply { + body.routerSettings(routerSettings) + } fun rpmLimit(rpmLimit: Long?) = apply { body.rpmLimit(rpmLimit) } @@ -695,6 +1323,23 @@ private constructor( */ fun rpmLimit(rpmLimit: JsonField) = apply { body.rpmLimit(rpmLimit) } + fun rpmLimitType(rpmLimitType: RpmLimitType?) = apply { body.rpmLimitType(rpmLimitType) } + + /** Alias for calling [Builder.rpmLimitType] with `rpmLimitType.orElse(null)`. */ + fun rpmLimitType(rpmLimitType: Optional) = + rpmLimitType(rpmLimitType.getOrNull()) + + /** + * Sets [Builder.rpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.rpmLimitType] with a well-typed [RpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rpmLimitType(rpmLimitType: JsonField) = apply { + body.rpmLimitType(rpmLimitType) + } + fun sendInviteEmail(sendInviteEmail: Boolean?) = apply { body.sendInviteEmail(sendInviteEmail) } @@ -816,6 +1461,23 @@ private constructor( */ fun tpmLimit(tpmLimit: JsonField) = apply { body.tpmLimit(tpmLimit) } + fun tpmLimitType(tpmLimitType: TpmLimitType?) = apply { body.tpmLimitType(tpmLimitType) } + + /** Alias for calling [Builder.tpmLimitType] with `tpmLimitType.orElse(null)`. */ + fun tpmLimitType(tpmLimitType: Optional) = + tpmLimitType(tpmLimitType.getOrNull()) + + /** + * Sets [Builder.tpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.tpmLimitType] with a well-typed [TpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tpmLimitType(tpmLimitType: JsonField) = apply { + body.tpmLimitType(tpmLimitType) + } + fun userId(userId: String?) = apply { body.userId(userId) } /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ @@ -953,19 +1615,19 @@ private constructor( */ fun build(): KeyGenerateParams = KeyGenerateParams( - llmChangedBy, + litellmChangedBy, body.build(), additionalHeaders.build(), additionalQueryParams.build(), ) } - @JvmSynthetic internal fun _body(): Body = body + fun _body(): Body = body override fun _headers(): Headers = Headers.builder() .apply { - llmChangedBy?.let { put("llm-changed-by", it) } + litellmChangedBy?.let { put("litellm-changed-by", it) } putAll(additionalHeaders) } .build() @@ -973,43 +1635,68 @@ private constructor( override fun _queryParams(): QueryParams = additionalQueryParams class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - private val aliases: JsonValue, + private val aliases: JsonField, private val allowedCacheControls: JsonField>, + private val allowedPassthroughRoutes: JsonField>, + private val allowedRoutes: JsonField>, + private val allowedVectorStoreIndexes: JsonField>, + private val autoRotate: JsonField, private val blocked: JsonField, private val budgetDuration: JsonField, private val budgetId: JsonField, - private val config: JsonValue, + private val config: JsonField, private val duration: JsonField, private val enforcedParams: JsonField>, private val guardrails: JsonField>, private val key: JsonField, private val keyAlias: JsonField, + private val keyType: JsonField, private val maxBudget: JsonField, private val maxParallelRequests: JsonField, - private val metadata: JsonValue, - private val modelMaxBudget: JsonValue, - private val modelRpmLimit: JsonValue, - private val modelTpmLimit: JsonValue, + private val metadata: JsonField, + private val modelMaxBudget: JsonField, + private val modelRpmLimit: JsonField, + private val modelTpmLimit: JsonField, private val models: JsonField>, - private val permissions: JsonValue, + private val objectPermission: JsonField, + private val organizationId: JsonField, + private val permissions: JsonField, + private val prompts: JsonField>, + private val rotationInterval: JsonField, + private val routerSettings: JsonField, private val rpmLimit: JsonField, + private val rpmLimitType: JsonField, private val sendInviteEmail: JsonField, private val softBudget: JsonField, private val spend: JsonField, private val tags: JsonField>, private val teamId: JsonField, private val tpmLimit: JsonField, + private val tpmLimitType: JsonField, private val userId: JsonField, private val additionalProperties: MutableMap, ) { @JsonCreator private constructor( - @JsonProperty("aliases") @ExcludeMissing aliases: JsonValue = JsonMissing.of(), + @JsonProperty("aliases") @ExcludeMissing aliases: JsonField = JsonMissing.of(), @JsonProperty("allowed_cache_controls") @ExcludeMissing allowedCacheControls: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_passthrough_routes") + @ExcludeMissing + allowedPassthroughRoutes: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_routes") + @ExcludeMissing + allowedRoutes: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_vector_store_indexes") + @ExcludeMissing + allowedVectorStoreIndexes: JsonField> = JsonMissing.of(), + @JsonProperty("auto_rotate") + @ExcludeMissing + autoRotate: JsonField = JsonMissing.of(), @JsonProperty("blocked") @ExcludeMissing blocked: JsonField = JsonMissing.of(), @JsonProperty("budget_duration") @ExcludeMissing @@ -1017,7 +1704,7 @@ private constructor( @JsonProperty("budget_id") @ExcludeMissing budgetId: JsonField = JsonMissing.of(), - @JsonProperty("config") @ExcludeMissing config: JsonValue = JsonMissing.of(), + @JsonProperty("config") @ExcludeMissing config: JsonField = JsonMissing.of(), @JsonProperty("duration") @ExcludeMissing duration: JsonField = JsonMissing.of(), @@ -1031,27 +1718,52 @@ private constructor( @JsonProperty("key_alias") @ExcludeMissing keyAlias: JsonField = JsonMissing.of(), + @JsonProperty("key_type") + @ExcludeMissing + keyType: JsonField = JsonMissing.of(), @JsonProperty("max_budget") @ExcludeMissing maxBudget: JsonField = JsonMissing.of(), @JsonProperty("max_parallel_requests") @ExcludeMissing maxParallelRequests: JsonField = JsonMissing.of(), - @JsonProperty("metadata") @ExcludeMissing metadata: JsonValue = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), @JsonProperty("model_max_budget") @ExcludeMissing - modelMaxBudget: JsonValue = JsonMissing.of(), + modelMaxBudget: JsonField = JsonMissing.of(), @JsonProperty("model_rpm_limit") @ExcludeMissing - modelRpmLimit: JsonValue = JsonMissing.of(), + modelRpmLimit: JsonField = JsonMissing.of(), @JsonProperty("model_tpm_limit") @ExcludeMissing - modelTpmLimit: JsonValue = JsonMissing.of(), + modelTpmLimit: JsonField = JsonMissing.of(), @JsonProperty("models") @ExcludeMissing models: JsonField> = JsonMissing.of(), - @JsonProperty("permissions") @ExcludeMissing permissions: JsonValue = JsonMissing.of(), + @JsonProperty("object_permission") + @ExcludeMissing + objectPermission: JsonField = JsonMissing.of(), + @JsonProperty("organization_id") + @ExcludeMissing + organizationId: JsonField = JsonMissing.of(), + @JsonProperty("permissions") + @ExcludeMissing + permissions: JsonField = JsonMissing.of(), + @JsonProperty("prompts") + @ExcludeMissing + prompts: JsonField> = JsonMissing.of(), + @JsonProperty("rotation_interval") + @ExcludeMissing + rotationInterval: JsonField = JsonMissing.of(), + @JsonProperty("router_settings") + @ExcludeMissing + routerSettings: JsonField = JsonMissing.of(), @JsonProperty("rpm_limit") @ExcludeMissing rpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("rpm_limit_type") + @ExcludeMissing + rpmLimitType: JsonField = JsonMissing.of(), @JsonProperty("send_invite_email") @ExcludeMissing sendInviteEmail: JsonField = JsonMissing.of(), @@ -1062,10 +1774,17 @@ private constructor( @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), @JsonProperty("team_id") @ExcludeMissing teamId: JsonField = JsonMissing.of(), @JsonProperty("tpm_limit") @ExcludeMissing tpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("tpm_limit_type") + @ExcludeMissing + tpmLimitType: JsonField = JsonMissing.of(), @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), ) : this( aliases, allowedCacheControls, + allowedPassthroughRoutes, + allowedRoutes, + allowedVectorStoreIndexes, + autoRotate, blocked, budgetDuration, budgetId, @@ -1075,6 +1794,7 @@ private constructor( guardrails, key, keyAlias, + keyType, maxBudget, maxParallelRequests, metadata, @@ -1082,164 +1802,280 @@ private constructor( modelRpmLimit, modelTpmLimit, models, + objectPermission, + organizationId, permissions, + prompts, + rotationInterval, + routerSettings, rpmLimit, + rpmLimitType, sendInviteEmail, softBudget, spend, tags, teamId, tpmLimit, + tpmLimitType, userId, mutableMapOf(), ) - @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonValue = aliases + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aliases(): Optional = aliases.getOptional("aliases") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun allowedCacheControls(): Optional> = - Optional.ofNullable(allowedCacheControls.getNullable("allowed_cache_controls")) + allowedCacheControls.getOptional("allowed_cache_controls") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun blocked(): Optional = Optional.ofNullable(blocked.getNullable("blocked")) + fun allowedPassthroughRoutes(): Optional> = + allowedPassthroughRoutes.getOptional("allowed_passthrough_routes") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetDuration(): Optional = - Optional.ofNullable(budgetDuration.getNullable("budget_duration")) + fun allowedRoutes(): Optional> = allowedRoutes.getOptional("allowed_routes") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetId(): Optional = Optional.ofNullable(budgetId.getNullable("budget_id")) + fun allowedVectorStoreIndexes(): Optional> = + allowedVectorStoreIndexes.getOptional("allowed_vector_store_indexes") - @JsonProperty("config") @ExcludeMissing fun _config(): JsonValue = config + /** + * Whether this key should be automatically rotated + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun autoRotate(): Optional = autoRotate.getOptional("auto_rotate") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun blocked(): Optional = blocked.getOptional("blocked") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun budgetDuration(): Optional = budgetDuration.getOptional("budget_duration") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun budgetId(): Optional = budgetId.getOptional("budget_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun config(): Optional = config.getOptional("config") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun duration(): Optional = duration.getOptional("duration") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun duration(): Optional = Optional.ofNullable(duration.getNullable("duration")) + fun enforcedParams(): Optional> = enforcedParams.getOptional("enforced_params") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun enforcedParams(): Optional> = - Optional.ofNullable(enforcedParams.getNullable("enforced_params")) + fun guardrails(): Optional> = guardrails.getOptional("guardrails") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun guardrails(): Optional> = - Optional.ofNullable(guardrails.getNullable("guardrails")) + fun key(): Optional = key.getOptional("key") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun key(): Optional = Optional.ofNullable(key.getNullable("key")) + fun keyAlias(): Optional = keyAlias.getOptional("key_alias") /** + * Enum for key types that determine what routes a key can access + * * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun keyAlias(): Optional = Optional.ofNullable(keyAlias.getNullable("key_alias")) + fun keyType(): Optional = keyType.getOptional("key_type") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun maxBudget(): Optional = Optional.ofNullable(maxBudget.getNullable("max_budget")) + fun maxBudget(): Optional = maxBudget.getOptional("max_budget") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun maxParallelRequests(): Optional = - Optional.ofNullable(maxParallelRequests.getNullable("max_parallel_requests")) + maxParallelRequests.getOptional("max_parallel_requests") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonValue = metadata + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelMaxBudget(): Optional = + modelMaxBudget.getOptional("model_max_budget") - @JsonProperty("model_max_budget") - @ExcludeMissing - fun _modelMaxBudget(): JsonValue = modelMaxBudget + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelRpmLimit(): Optional = modelRpmLimit.getOptional("model_rpm_limit") - @JsonProperty("model_rpm_limit") - @ExcludeMissing - fun _modelRpmLimit(): JsonValue = modelRpmLimit + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelTpmLimit(): Optional = modelTpmLimit.getOptional("model_tpm_limit") - @JsonProperty("model_tpm_limit") - @ExcludeMissing - fun _modelTpmLimit(): JsonValue = modelTpmLimit + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun models(): Optional> = models.getOptional("models") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun objectPermission(): Optional = + objectPermission.getOptional("object_permission") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun organizationId(): Optional = organizationId.getOptional("organization_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun permissions(): Optional = permissions.getOptional("permissions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun prompts(): Optional> = prompts.getOptional("prompts") + + /** + * How often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rotationInterval(): Optional = rotationInterval.getOptional("rotation_interval") + + /** + * Set of params that you can modify via `router.update_settings()`. + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routerSettings(): Optional = + routerSettings.getOptional("router_settings") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun models(): Optional> = Optional.ofNullable(models.getNullable("models")) + fun rpmLimit(): Optional = rpmLimit.getOptional("rpm_limit") - @JsonProperty("permissions") @ExcludeMissing fun _permissions(): JsonValue = permissions + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rpmLimitType(): Optional = rpmLimitType.getOptional("rpm_limit_type") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rpmLimit(): Optional = Optional.ofNullable(rpmLimit.getNullable("rpm_limit")) + fun sendInviteEmail(): Optional = sendInviteEmail.getOptional("send_invite_email") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun sendInviteEmail(): Optional = - Optional.ofNullable(sendInviteEmail.getNullable("send_invite_email")) + fun softBudget(): Optional = softBudget.getOptional("soft_budget") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun softBudget(): Optional = - Optional.ofNullable(softBudget.getNullable("soft_budget")) + fun spend(): Optional = spend.getOptional("spend") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spend(): Optional = Optional.ofNullable(spend.getNullable("spend")) + fun tags(): Optional> = tags.getOptional("tags") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tags(): Optional> = Optional.ofNullable(tags.getNullable("tags")) + fun teamId(): Optional = teamId.getOptional("team_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun teamId(): Optional = Optional.ofNullable(teamId.getNullable("team_id")) + fun tpmLimit(): Optional = tpmLimit.getOptional("tpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tpmLimit(): Optional = Optional.ofNullable(tpmLimit.getNullable("tpm_limit")) + fun tpmLimitType(): Optional = tpmLimitType.getOptional("tpm_limit_type") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [aliases]. + * + * Unlike [aliases], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonField = aliases /** * Returns the raw JSON value of [allowedCacheControls]. @@ -1251,6 +2087,46 @@ private constructor( @ExcludeMissing fun _allowedCacheControls(): JsonField> = allowedCacheControls + /** + * Returns the raw JSON value of [allowedPassthroughRoutes]. + * + * Unlike [allowedPassthroughRoutes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("allowed_passthrough_routes") + @ExcludeMissing + fun _allowedPassthroughRoutes(): JsonField> = allowedPassthroughRoutes + + /** + * Returns the raw JSON value of [allowedRoutes]. + * + * Unlike [allowedRoutes], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("allowed_routes") + @ExcludeMissing + fun _allowedRoutes(): JsonField> = allowedRoutes + + /** + * Returns the raw JSON value of [allowedVectorStoreIndexes]. + * + * Unlike [allowedVectorStoreIndexes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("allowed_vector_store_indexes") + @ExcludeMissing + fun _allowedVectorStoreIndexes(): JsonField> = + allowedVectorStoreIndexes + + /** + * Returns the raw JSON value of [autoRotate]. + * + * Unlike [autoRotate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("auto_rotate") + @ExcludeMissing + fun _autoRotate(): JsonField = autoRotate + /** * Returns the raw JSON value of [blocked]. * @@ -1275,6 +2151,13 @@ private constructor( */ @JsonProperty("budget_id") @ExcludeMissing fun _budgetId(): JsonField = budgetId + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config") @ExcludeMissing fun _config(): JsonField = config + /** * Returns the raw JSON value of [duration]. * @@ -1316,11 +2199,18 @@ private constructor( @JsonProperty("key_alias") @ExcludeMissing fun _keyAlias(): JsonField = keyAlias /** - * Returns the raw JSON value of [maxBudget]. + * Returns the raw JSON value of [keyType]. * - * Unlike [maxBudget], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [keyType], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("max_budget") @ExcludeMissing fun _maxBudget(): JsonField = maxBudget + @JsonProperty("key_type") @ExcludeMissing fun _keyType(): JsonField = keyType + + /** + * Returns the raw JSON value of [maxBudget]. + * + * Unlike [maxBudget], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("max_budget") @ExcludeMissing fun _maxBudget(): JsonField = maxBudget /** * Returns the raw JSON value of [maxParallelRequests]. @@ -1332,6 +2222,43 @@ private constructor( @ExcludeMissing fun _maxParallelRequests(): JsonField = maxParallelRequests + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [modelMaxBudget]. + * + * Unlike [modelMaxBudget], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("model_max_budget") + @ExcludeMissing + fun _modelMaxBudget(): JsonField = modelMaxBudget + + /** + * Returns the raw JSON value of [modelRpmLimit]. + * + * Unlike [modelRpmLimit], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("model_rpm_limit") + @ExcludeMissing + fun _modelRpmLimit(): JsonField = modelRpmLimit + + /** + * Returns the raw JSON value of [modelTpmLimit]. + * + * Unlike [modelTpmLimit], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("model_tpm_limit") + @ExcludeMissing + fun _modelTpmLimit(): JsonField = modelTpmLimit + /** * Returns the raw JSON value of [models]. * @@ -1339,6 +2266,62 @@ private constructor( */ @JsonProperty("models") @ExcludeMissing fun _models(): JsonField> = models + /** + * Returns the raw JSON value of [objectPermission]. + * + * Unlike [objectPermission], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("object_permission") + @ExcludeMissing + fun _objectPermission(): JsonField = objectPermission + + /** + * Returns the raw JSON value of [organizationId]. + * + * Unlike [organizationId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("organization_id") + @ExcludeMissing + fun _organizationId(): JsonField = organizationId + + /** + * Returns the raw JSON value of [permissions]. + * + * Unlike [permissions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permissions") + @ExcludeMissing + fun _permissions(): JsonField = permissions + + /** + * Returns the raw JSON value of [prompts]. + * + * Unlike [prompts], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prompts") @ExcludeMissing fun _prompts(): JsonField> = prompts + + /** + * Returns the raw JSON value of [rotationInterval]. + * + * Unlike [rotationInterval], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("rotation_interval") + @ExcludeMissing + fun _rotationInterval(): JsonField = rotationInterval + + /** + * Returns the raw JSON value of [routerSettings]. + * + * Unlike [routerSettings], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("router_settings") + @ExcludeMissing + fun _routerSettings(): JsonField = routerSettings + /** * Returns the raw JSON value of [rpmLimit]. * @@ -1346,6 +2329,16 @@ private constructor( */ @JsonProperty("rpm_limit") @ExcludeMissing fun _rpmLimit(): JsonField = rpmLimit + /** + * Returns the raw JSON value of [rpmLimitType]. + * + * Unlike [rpmLimitType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("rpm_limit_type") + @ExcludeMissing + fun _rpmLimitType(): JsonField = rpmLimitType + /** * Returns the raw JSON value of [sendInviteEmail]. * @@ -1393,6 +2386,16 @@ private constructor( */ @JsonProperty("tpm_limit") @ExcludeMissing fun _tpmLimit(): JsonField = tpmLimit + /** + * Returns the raw JSON value of [tpmLimitType]. + * + * Unlike [tpmLimitType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tpm_limit_type") + @ExcludeMissing + fun _tpmLimitType(): JsonField = tpmLimitType + /** * Returns the raw JSON value of [userId]. * @@ -1421,32 +2424,46 @@ private constructor( /** A builder for [Body]. */ class Builder internal constructor() { - private var aliases: JsonValue = JsonMissing.of() + private var aliases: JsonField = JsonMissing.of() private var allowedCacheControls: JsonField>? = null + private var allowedPassthroughRoutes: JsonField>? = null + private var allowedRoutes: JsonField>? = null + private var allowedVectorStoreIndexes: + JsonField>? = + null + private var autoRotate: JsonField = JsonMissing.of() private var blocked: JsonField = JsonMissing.of() private var budgetDuration: JsonField = JsonMissing.of() private var budgetId: JsonField = JsonMissing.of() - private var config: JsonValue = JsonMissing.of() + private var config: JsonField = JsonMissing.of() private var duration: JsonField = JsonMissing.of() private var enforcedParams: JsonField>? = null private var guardrails: JsonField>? = null private var key: JsonField = JsonMissing.of() private var keyAlias: JsonField = JsonMissing.of() + private var keyType: JsonField = JsonMissing.of() private var maxBudget: JsonField = JsonMissing.of() private var maxParallelRequests: JsonField = JsonMissing.of() - private var metadata: JsonValue = JsonMissing.of() - private var modelMaxBudget: JsonValue = JsonMissing.of() - private var modelRpmLimit: JsonValue = JsonMissing.of() - private var modelTpmLimit: JsonValue = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var modelMaxBudget: JsonField = JsonMissing.of() + private var modelRpmLimit: JsonField = JsonMissing.of() + private var modelTpmLimit: JsonField = JsonMissing.of() private var models: JsonField>? = null - private var permissions: JsonValue = JsonMissing.of() + private var objectPermission: JsonField = JsonMissing.of() + private var organizationId: JsonField = JsonMissing.of() + private var permissions: JsonField = JsonMissing.of() + private var prompts: JsonField>? = null + private var rotationInterval: JsonField = JsonMissing.of() + private var routerSettings: JsonField = JsonMissing.of() private var rpmLimit: JsonField = JsonMissing.of() + private var rpmLimitType: JsonField = JsonMissing.of() private var sendInviteEmail: JsonField = JsonMissing.of() private var softBudget: JsonField = JsonMissing.of() private var spend: JsonField = JsonMissing.of() private var tags: JsonField>? = null private var teamId: JsonField = JsonMissing.of() private var tpmLimit: JsonField = JsonMissing.of() + private var tpmLimitType: JsonField = JsonMissing.of() private var userId: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @@ -1454,6 +2471,11 @@ private constructor( internal fun from(body: Body) = apply { aliases = body.aliases allowedCacheControls = body.allowedCacheControls.map { it.toMutableList() } + allowedPassthroughRoutes = body.allowedPassthroughRoutes.map { it.toMutableList() } + allowedRoutes = body.allowedRoutes.map { it.toMutableList() } + allowedVectorStoreIndexes = + body.allowedVectorStoreIndexes.map { it.toMutableList() } + autoRotate = body.autoRotate blocked = body.blocked budgetDuration = body.budgetDuration budgetId = body.budgetId @@ -1463,6 +2485,7 @@ private constructor( guardrails = body.guardrails.map { it.toMutableList() } key = body.key keyAlias = body.keyAlias + keyType = body.keyType maxBudget = body.maxBudget maxParallelRequests = body.maxParallelRequests metadata = body.metadata @@ -1470,19 +2493,38 @@ private constructor( modelRpmLimit = body.modelRpmLimit modelTpmLimit = body.modelTpmLimit models = body.models.map { it.toMutableList() } + objectPermission = body.objectPermission + organizationId = body.organizationId permissions = body.permissions + prompts = body.prompts.map { it.toMutableList() } + rotationInterval = body.rotationInterval + routerSettings = body.routerSettings rpmLimit = body.rpmLimit + rpmLimitType = body.rpmLimitType sendInviteEmail = body.sendInviteEmail softBudget = body.softBudget spend = body.spend tags = body.tags.map { it.toMutableList() } teamId = body.teamId tpmLimit = body.tpmLimit + tpmLimitType = body.tpmLimitType userId = body.userId additionalProperties = body.additionalProperties.toMutableMap() } - fun aliases(aliases: JsonValue) = apply { this.aliases = aliases } + fun aliases(aliases: Aliases?) = aliases(JsonField.ofNullable(aliases)) + + /** Alias for calling [Builder.aliases] with `aliases.orElse(null)`. */ + fun aliases(aliases: Optional) = aliases(aliases.getOrNull()) + + /** + * Sets [Builder.aliases] to an arbitrary JSON value. + * + * You should usually call [Builder.aliases] with a well-typed [Aliases] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun aliases(aliases: JsonField) = apply { this.aliases = aliases } fun allowedCacheControls(allowedCacheControls: List?) = allowedCacheControls(JsonField.ofNullable(allowedCacheControls)) @@ -1517,6 +2559,132 @@ private constructor( } } + fun allowedPassthroughRoutes(allowedPassthroughRoutes: List?) = + allowedPassthroughRoutes(JsonField.ofNullable(allowedPassthroughRoutes)) + + /** + * Alias for calling [Builder.allowedPassthroughRoutes] with + * `allowedPassthroughRoutes.orElse(null)`. + */ + fun allowedPassthroughRoutes(allowedPassthroughRoutes: Optional>) = + allowedPassthroughRoutes(allowedPassthroughRoutes.getOrNull()) + + /** + * Sets [Builder.allowedPassthroughRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedPassthroughRoutes] with a well-typed + * `List` value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun allowedPassthroughRoutes(allowedPassthroughRoutes: JsonField>) = + apply { + this.allowedPassthroughRoutes = + allowedPassthroughRoutes.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [allowedPassthroughRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedPassthroughRoute(allowedPassthroughRoute: JsonValue) = apply { + allowedPassthroughRoutes = + (allowedPassthroughRoutes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedPassthroughRoutes", it).add(allowedPassthroughRoute) + } + } + + fun allowedRoutes(allowedRoutes: List?) = + allowedRoutes(JsonField.ofNullable(allowedRoutes)) + + /** Alias for calling [Builder.allowedRoutes] with `allowedRoutes.orElse(null)`. */ + fun allowedRoutes(allowedRoutes: Optional>) = + allowedRoutes(allowedRoutes.getOrNull()) + + /** + * Sets [Builder.allowedRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedRoutes] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun allowedRoutes(allowedRoutes: JsonField>) = apply { + this.allowedRoutes = allowedRoutes.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [allowedRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedRoute(allowedRoute: JsonValue) = apply { + allowedRoutes = + (allowedRoutes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedRoutes", it).add(allowedRoute) + } + } + + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: List? + ) = allowedVectorStoreIndexes(JsonField.ofNullable(allowedVectorStoreIndexes)) + + /** + * Alias for calling [Builder.allowedVectorStoreIndexes] with + * `allowedVectorStoreIndexes.orElse(null)`. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: Optional> + ) = allowedVectorStoreIndexes(allowedVectorStoreIndexes.getOrNull()) + + /** + * Sets [Builder.allowedVectorStoreIndexes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedVectorStoreIndexes] with a well-typed + * `List` value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: JsonField> + ) = apply { + this.allowedVectorStoreIndexes = + allowedVectorStoreIndexes.map { it.toMutableList() } + } + + /** + * Adds a single [AllowedVectorStoreIndex] to [allowedVectorStoreIndexes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedVectorStoreIndex(allowedVectorStoreIndex: AllowedVectorStoreIndex) = + apply { + allowedVectorStoreIndexes = + (allowedVectorStoreIndexes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedVectorStoreIndexes", it).add(allowedVectorStoreIndex) + } + } + + /** Whether this key should be automatically rotated */ + fun autoRotate(autoRotate: Boolean?) = autoRotate(JsonField.ofNullable(autoRotate)) + + /** + * Alias for [Builder.autoRotate]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun autoRotate(autoRotate: Boolean) = autoRotate(autoRotate as Boolean?) + + /** Alias for calling [Builder.autoRotate] with `autoRotate.orElse(null)`. */ + fun autoRotate(autoRotate: Optional) = autoRotate(autoRotate.getOrNull()) + + /** + * Sets [Builder.autoRotate] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRotate] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun autoRotate(autoRotate: JsonField) = apply { this.autoRotate = autoRotate } + fun blocked(blocked: Boolean?) = blocked(JsonField.ofNullable(blocked)) /** @@ -1570,7 +2738,19 @@ private constructor( */ fun budgetId(budgetId: JsonField) = apply { this.budgetId = budgetId } - fun config(config: JsonValue) = apply { this.config = config } + fun config(config: Config?) = config(JsonField.ofNullable(config)) + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [Config] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun config(config: JsonField) = apply { this.config = config } fun duration(duration: String?) = duration(JsonField.ofNullable(duration)) @@ -1672,6 +2852,21 @@ private constructor( */ fun keyAlias(keyAlias: JsonField) = apply { this.keyAlias = keyAlias } + /** Enum for key types that determine what routes a key can access */ + fun keyType(keyType: KeyType?) = keyType(JsonField.ofNullable(keyType)) + + /** Alias for calling [Builder.keyType] with `keyType.orElse(null)`. */ + fun keyType(keyType: Optional) = keyType(keyType.getOrNull()) + + /** + * Sets [Builder.keyType] to an arbitrary JSON value. + * + * You should usually call [Builder.keyType] with a well-typed [KeyType] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun keyType(keyType: JsonField) = apply { this.keyType = keyType } + fun maxBudget(maxBudget: Double?) = maxBudget(JsonField.ofNullable(maxBudget)) /** @@ -1722,17 +2917,71 @@ private constructor( this.maxParallelRequests = maxParallelRequests } - fun metadata(metadata: JsonValue) = apply { this.metadata = metadata } + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) - fun modelMaxBudget(modelMaxBudget: JsonValue) = apply { + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun modelMaxBudget(modelMaxBudget: ModelMaxBudget?) = + modelMaxBudget(JsonField.ofNullable(modelMaxBudget)) + + /** Alias for calling [Builder.modelMaxBudget] with `modelMaxBudget.orElse(null)`. */ + fun modelMaxBudget(modelMaxBudget: Optional) = + modelMaxBudget(modelMaxBudget.getOrNull()) + + /** + * Sets [Builder.modelMaxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.modelMaxBudget] with a well-typed [ModelMaxBudget] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun modelMaxBudget(modelMaxBudget: JsonField) = apply { this.modelMaxBudget = modelMaxBudget } - fun modelRpmLimit(modelRpmLimit: JsonValue) = apply { + fun modelRpmLimit(modelRpmLimit: ModelRpmLimit?) = + modelRpmLimit(JsonField.ofNullable(modelRpmLimit)) + + /** Alias for calling [Builder.modelRpmLimit] with `modelRpmLimit.orElse(null)`. */ + fun modelRpmLimit(modelRpmLimit: Optional) = + modelRpmLimit(modelRpmLimit.getOrNull()) + + /** + * Sets [Builder.modelRpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.modelRpmLimit] with a well-typed [ModelRpmLimit] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun modelRpmLimit(modelRpmLimit: JsonField) = apply { this.modelRpmLimit = modelRpmLimit } - fun modelTpmLimit(modelTpmLimit: JsonValue) = apply { + fun modelTpmLimit(modelTpmLimit: ModelTpmLimit?) = + modelTpmLimit(JsonField.ofNullable(modelTpmLimit)) + + /** Alias for calling [Builder.modelTpmLimit] with `modelTpmLimit.orElse(null)`. */ + fun modelTpmLimit(modelTpmLimit: Optional) = + modelTpmLimit(modelTpmLimit.getOrNull()) + + /** + * Sets [Builder.modelTpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.modelTpmLimit] with a well-typed [ModelTpmLimit] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun modelTpmLimit(modelTpmLimit: JsonField) = apply { this.modelTpmLimit = modelTpmLimit } @@ -1764,96 +3013,236 @@ private constructor( } } - fun permissions(permissions: JsonValue) = apply { this.permissions = permissions } + fun objectPermission(objectPermission: ObjectPermission?) = + objectPermission(JsonField.ofNullable(objectPermission)) - fun rpmLimit(rpmLimit: Long?) = rpmLimit(JsonField.ofNullable(rpmLimit)) + /** + * Alias for calling [Builder.objectPermission] with `objectPermission.orElse(null)`. + */ + fun objectPermission(objectPermission: Optional) = + objectPermission(objectPermission.getOrNull()) /** - * Alias for [Builder.rpmLimit]. + * Sets [Builder.objectPermission] to an arbitrary JSON value. * - * This unboxed primitive overload exists for backwards compatibility. + * You should usually call [Builder.objectPermission] with a well-typed + * [ObjectPermission] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. */ - fun rpmLimit(rpmLimit: Long) = rpmLimit(rpmLimit as Long?) + fun objectPermission(objectPermission: JsonField) = apply { + this.objectPermission = objectPermission + } - /** Alias for calling [Builder.rpmLimit] with `rpmLimit.orElse(null)`. */ - fun rpmLimit(rpmLimit: Optional) = rpmLimit(rpmLimit.getOrNull()) + fun organizationId(organizationId: String?) = + organizationId(JsonField.ofNullable(organizationId)) + + /** Alias for calling [Builder.organizationId] with `organizationId.orElse(null)`. */ + fun organizationId(organizationId: Optional) = + organizationId(organizationId.getOrNull()) /** - * Sets [Builder.rpmLimit] to an arbitrary JSON value. + * Sets [Builder.organizationId] to an arbitrary JSON value. * - * You should usually call [Builder.rpmLimit] with a well-typed [Long] value instead. - * This method is primarily for setting the field to an undocumented or not yet + * You should usually call [Builder.organizationId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet * supported value. */ - fun rpmLimit(rpmLimit: JsonField) = apply { this.rpmLimit = rpmLimit } + fun organizationId(organizationId: JsonField) = apply { + this.organizationId = organizationId + } - fun sendInviteEmail(sendInviteEmail: Boolean?) = - sendInviteEmail(JsonField.ofNullable(sendInviteEmail)) + fun permissions(permissions: Permissions?) = + permissions(JsonField.ofNullable(permissions)) + + /** Alias for calling [Builder.permissions] with `permissions.orElse(null)`. */ + fun permissions(permissions: Optional) = + permissions(permissions.getOrNull()) /** - * Alias for [Builder.sendInviteEmail]. + * Sets [Builder.permissions] to an arbitrary JSON value. * - * This unboxed primitive overload exists for backwards compatibility. + * You should usually call [Builder.permissions] with a well-typed [Permissions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun sendInviteEmail(sendInviteEmail: Boolean) = - sendInviteEmail(sendInviteEmail as Boolean?) + fun permissions(permissions: JsonField) = apply { + this.permissions = permissions + } - /** Alias for calling [Builder.sendInviteEmail] with `sendInviteEmail.orElse(null)`. */ - fun sendInviteEmail(sendInviteEmail: Optional) = - sendInviteEmail(sendInviteEmail.getOrNull()) + fun prompts(prompts: List?) = prompts(JsonField.ofNullable(prompts)) + + /** Alias for calling [Builder.prompts] with `prompts.orElse(null)`. */ + fun prompts(prompts: Optional>) = prompts(prompts.getOrNull()) /** - * Sets [Builder.sendInviteEmail] to an arbitrary JSON value. + * Sets [Builder.prompts] to an arbitrary JSON value. * - * You should usually call [Builder.sendInviteEmail] with a well-typed [Boolean] value + * You should usually call [Builder.prompts] with a well-typed `List` value * instead. This method is primarily for setting the field to an undocumented or not yet * supported value. */ - fun sendInviteEmail(sendInviteEmail: JsonField) = apply { - this.sendInviteEmail = sendInviteEmail + fun prompts(prompts: JsonField>) = apply { + this.prompts = prompts.map { it.toMutableList() } } - fun softBudget(softBudget: Double?) = softBudget(JsonField.ofNullable(softBudget)) - /** - * Alias for [Builder.softBudget]. + * Adds a single [String] to [prompts]. * - * This unboxed primitive overload exists for backwards compatibility. + * @throws IllegalStateException if the field was previously set to a non-list. */ - fun softBudget(softBudget: Double) = softBudget(softBudget as Double?) + fun addPrompt(prompt: String) = apply { + prompts = + (prompts ?: JsonField.of(mutableListOf())).also { + checkKnown("prompts", it).add(prompt) + } + } - /** Alias for calling [Builder.softBudget] with `softBudget.orElse(null)`. */ - fun softBudget(softBudget: Optional) = softBudget(softBudget.getOrNull()) + /** How often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True */ + fun rotationInterval(rotationInterval: String?) = + rotationInterval(JsonField.ofNullable(rotationInterval)) /** - * Sets [Builder.softBudget] to an arbitrary JSON value. + * Alias for calling [Builder.rotationInterval] with `rotationInterval.orElse(null)`. + */ + fun rotationInterval(rotationInterval: Optional) = + rotationInterval(rotationInterval.getOrNull()) + + /** + * Sets [Builder.rotationInterval] to an arbitrary JSON value. * - * You should usually call [Builder.softBudget] with a well-typed [Double] value + * You should usually call [Builder.rotationInterval] with a well-typed [String] value * instead. This method is primarily for setting the field to an undocumented or not yet * supported value. */ - fun softBudget(softBudget: JsonField) = apply { this.softBudget = softBudget } + fun rotationInterval(rotationInterval: JsonField) = apply { + this.rotationInterval = rotationInterval + } - fun spend(spend: Double?) = spend(JsonField.ofNullable(spend)) + /** Set of params that you can modify via `router.update_settings()`. */ + fun routerSettings(routerSettings: RouterSettings?) = + routerSettings(JsonField.ofNullable(routerSettings)) + + /** Alias for calling [Builder.routerSettings] with `routerSettings.orElse(null)`. */ + fun routerSettings(routerSettings: Optional) = + routerSettings(routerSettings.getOrNull()) /** - * Alias for [Builder.spend]. + * Sets [Builder.routerSettings] to an arbitrary JSON value. * - * This unboxed primitive overload exists for backwards compatibility. + * You should usually call [Builder.routerSettings] with a well-typed [RouterSettings] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. */ - fun spend(spend: Double) = spend(spend as Double?) + fun routerSettings(routerSettings: JsonField) = apply { + this.routerSettings = routerSettings + } - /** Alias for calling [Builder.spend] with `spend.orElse(null)`. */ - fun spend(spend: Optional) = spend(spend.getOrNull()) + fun rpmLimit(rpmLimit: Long?) = rpmLimit(JsonField.ofNullable(rpmLimit)) /** - * Sets [Builder.spend] to an arbitrary JSON value. + * Alias for [Builder.rpmLimit]. * - * You should usually call [Builder.spend] with a well-typed [Double] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. + * This unboxed primitive overload exists for backwards compatibility. */ - fun spend(spend: JsonField) = apply { this.spend = spend } + fun rpmLimit(rpmLimit: Long) = rpmLimit(rpmLimit as Long?) + + /** Alias for calling [Builder.rpmLimit] with `rpmLimit.orElse(null)`. */ + fun rpmLimit(rpmLimit: Optional) = rpmLimit(rpmLimit.getOrNull()) + + /** + * Sets [Builder.rpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.rpmLimit] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rpmLimit(rpmLimit: JsonField) = apply { this.rpmLimit = rpmLimit } + + fun rpmLimitType(rpmLimitType: RpmLimitType?) = + rpmLimitType(JsonField.ofNullable(rpmLimitType)) + + /** Alias for calling [Builder.rpmLimitType] with `rpmLimitType.orElse(null)`. */ + fun rpmLimitType(rpmLimitType: Optional) = + rpmLimitType(rpmLimitType.getOrNull()) + + /** + * Sets [Builder.rpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.rpmLimitType] with a well-typed [RpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rpmLimitType(rpmLimitType: JsonField) = apply { + this.rpmLimitType = rpmLimitType + } + + fun sendInviteEmail(sendInviteEmail: Boolean?) = + sendInviteEmail(JsonField.ofNullable(sendInviteEmail)) + + /** + * Alias for [Builder.sendInviteEmail]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun sendInviteEmail(sendInviteEmail: Boolean) = + sendInviteEmail(sendInviteEmail as Boolean?) + + /** Alias for calling [Builder.sendInviteEmail] with `sendInviteEmail.orElse(null)`. */ + fun sendInviteEmail(sendInviteEmail: Optional) = + sendInviteEmail(sendInviteEmail.getOrNull()) + + /** + * Sets [Builder.sendInviteEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.sendInviteEmail] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sendInviteEmail(sendInviteEmail: JsonField) = apply { + this.sendInviteEmail = sendInviteEmail + } + + fun softBudget(softBudget: Double?) = softBudget(JsonField.ofNullable(softBudget)) + + /** + * Alias for [Builder.softBudget]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun softBudget(softBudget: Double) = softBudget(softBudget as Double?) + + /** Alias for calling [Builder.softBudget] with `softBudget.orElse(null)`. */ + fun softBudget(softBudget: Optional) = softBudget(softBudget.getOrNull()) + + /** + * Sets [Builder.softBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.softBudget] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun softBudget(softBudget: JsonField) = apply { this.softBudget = softBudget } + + fun spend(spend: Double?) = spend(JsonField.ofNullable(spend)) + + /** + * Alias for [Builder.spend]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun spend(spend: Double) = spend(spend as Double?) + + /** Alias for calling [Builder.spend] with `spend.orElse(null)`. */ + fun spend(spend: Optional) = spend(spend.getOrNull()) + + /** + * Sets [Builder.spend] to an arbitrary JSON value. + * + * You should usually call [Builder.spend] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spend(spend: JsonField) = apply { this.spend = spend } fun tags(tags: List?) = tags(JsonField.ofNullable(tags)) @@ -1916,6 +3305,24 @@ private constructor( */ fun tpmLimit(tpmLimit: JsonField) = apply { this.tpmLimit = tpmLimit } + fun tpmLimitType(tpmLimitType: TpmLimitType?) = + tpmLimitType(JsonField.ofNullable(tpmLimitType)) + + /** Alias for calling [Builder.tpmLimitType] with `tpmLimitType.orElse(null)`. */ + fun tpmLimitType(tpmLimitType: Optional) = + tpmLimitType(tpmLimitType.getOrNull()) + + /** + * Sets [Builder.tpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.tpmLimitType] with a well-typed [TpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tpmLimitType(tpmLimitType: JsonField) = apply { + this.tpmLimitType = tpmLimitType + } + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ @@ -1958,6 +3365,10 @@ private constructor( Body( aliases, (allowedCacheControls ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedPassthroughRoutes ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedRoutes ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedVectorStoreIndexes ?: JsonMissing.of()).map { it.toImmutable() }, + autoRotate, blocked, budgetDuration, budgetId, @@ -1967,6 +3378,7 @@ private constructor( (guardrails ?: JsonMissing.of()).map { it.toImmutable() }, key, keyAlias, + keyType, maxBudget, maxParallelRequests, metadata, @@ -1974,14 +3386,21 @@ private constructor( modelRpmLimit, modelTpmLimit, (models ?: JsonMissing.of()).map { it.toImmutable() }, + objectPermission, + organizationId, permissions, + (prompts ?: JsonMissing.of()).map { it.toImmutable() }, + rotationInterval, + routerSettings, rpmLimit, + rpmLimitType, sendInviteEmail, softBudget, spend, (tags ?: JsonMissing.of()).map { it.toImmutable() }, teamId, tpmLimit, + tpmLimitType, userId, additionalProperties.toMutableMap(), ) @@ -1994,45 +3413,3462 @@ private constructor( return@apply } + aliases().ifPresent { it.validate() } allowedCacheControls() + allowedPassthroughRoutes() + allowedRoutes() + allowedVectorStoreIndexes().ifPresent { it.forEach { it.validate() } } + autoRotate() blocked() budgetDuration() budgetId() + config().ifPresent { it.validate() } duration() enforcedParams() guardrails() key() keyAlias() + keyType().ifPresent { it.validate() } maxBudget() maxParallelRequests() + metadata().ifPresent { it.validate() } + modelMaxBudget().ifPresent { it.validate() } + modelRpmLimit().ifPresent { it.validate() } + modelTpmLimit().ifPresent { it.validate() } models() + objectPermission().ifPresent { it.validate() } + organizationId() + permissions().ifPresent { it.validate() } + prompts() + rotationInterval() + routerSettings().ifPresent { it.validate() } rpmLimit() + rpmLimitType().ifPresent { it.validate() } sendInviteEmail() softBudget() spend() tags() teamId() tpmLimit() + tpmLimitType().ifPresent { it.validate() } userId() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aliases.asKnown().getOrNull()?.validity() ?: 0) + + (allowedCacheControls.asKnown().getOrNull()?.size ?: 0) + + (allowedPassthroughRoutes.asKnown().getOrNull()?.size ?: 0) + + (allowedRoutes.asKnown().getOrNull()?.size ?: 0) + + (allowedVectorStoreIndexes.asKnown().getOrNull()?.sumOf { it.validity().toInt() } + ?: 0) + + (if (autoRotate.asKnown().isPresent) 1 else 0) + + (if (blocked.asKnown().isPresent) 1 else 0) + + (if (budgetDuration.asKnown().isPresent) 1 else 0) + + (if (budgetId.asKnown().isPresent) 1 else 0) + + (config.asKnown().getOrNull()?.validity() ?: 0) + + (if (duration.asKnown().isPresent) 1 else 0) + + (enforcedParams.asKnown().getOrNull()?.size ?: 0) + + (guardrails.asKnown().getOrNull()?.size ?: 0) + + (if (key.asKnown().isPresent) 1 else 0) + + (if (keyAlias.asKnown().isPresent) 1 else 0) + + (keyType.asKnown().getOrNull()?.validity() ?: 0) + + (if (maxBudget.asKnown().isPresent) 1 else 0) + + (if (maxParallelRequests.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (modelMaxBudget.asKnown().getOrNull()?.validity() ?: 0) + + (modelRpmLimit.asKnown().getOrNull()?.validity() ?: 0) + + (modelTpmLimit.asKnown().getOrNull()?.validity() ?: 0) + + (models.asKnown().getOrNull()?.size ?: 0) + + (objectPermission.asKnown().getOrNull()?.validity() ?: 0) + + (if (organizationId.asKnown().isPresent) 1 else 0) + + (permissions.asKnown().getOrNull()?.validity() ?: 0) + + (prompts.asKnown().getOrNull()?.size ?: 0) + + (if (rotationInterval.asKnown().isPresent) 1 else 0) + + (routerSettings.asKnown().getOrNull()?.validity() ?: 0) + + (if (rpmLimit.asKnown().isPresent) 1 else 0) + + (rpmLimitType.asKnown().getOrNull()?.validity() ?: 0) + + (if (sendInviteEmail.asKnown().isPresent) 1 else 0) + + (if (softBudget.asKnown().isPresent) 1 else 0) + + (if (spend.asKnown().isPresent) 1 else 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + (if (teamId.asKnown().isPresent) 1 else 0) + + (if (tpmLimit.asKnown().isPresent) 1 else 0) + + (tpmLimitType.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && aliases == other.aliases && allowedCacheControls == other.allowedCacheControls && blocked == other.blocked && budgetDuration == other.budgetDuration && budgetId == other.budgetId && config == other.config && duration == other.duration && enforcedParams == other.enforcedParams && guardrails == other.guardrails && key == other.key && keyAlias == other.keyAlias && maxBudget == other.maxBudget && maxParallelRequests == other.maxParallelRequests && metadata == other.metadata && modelMaxBudget == other.modelMaxBudget && modelRpmLimit == other.modelRpmLimit && modelTpmLimit == other.modelTpmLimit && models == other.models && permissions == other.permissions && rpmLimit == other.rpmLimit && sendInviteEmail == other.sendInviteEmail && softBudget == other.softBudget && spend == other.spend && tags == other.tags && teamId == other.teamId && tpmLimit == other.tpmLimit && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Body && + aliases == other.aliases && + allowedCacheControls == other.allowedCacheControls && + allowedPassthroughRoutes == other.allowedPassthroughRoutes && + allowedRoutes == other.allowedRoutes && + allowedVectorStoreIndexes == other.allowedVectorStoreIndexes && + autoRotate == other.autoRotate && + blocked == other.blocked && + budgetDuration == other.budgetDuration && + budgetId == other.budgetId && + config == other.config && + duration == other.duration && + enforcedParams == other.enforcedParams && + guardrails == other.guardrails && + key == other.key && + keyAlias == other.keyAlias && + keyType == other.keyType && + maxBudget == other.maxBudget && + maxParallelRequests == other.maxParallelRequests && + metadata == other.metadata && + modelMaxBudget == other.modelMaxBudget && + modelRpmLimit == other.modelRpmLimit && + modelTpmLimit == other.modelTpmLimit && + models == other.models && + objectPermission == other.objectPermission && + organizationId == other.organizationId && + permissions == other.permissions && + prompts == other.prompts && + rotationInterval == other.rotationInterval && + routerSettings == other.routerSettings && + rpmLimit == other.rpmLimit && + rpmLimitType == other.rpmLimitType && + sendInviteEmail == other.sendInviteEmail && + softBudget == other.softBudget && + spend == other.spend && + tags == other.tags && + teamId == other.teamId && + tpmLimit == other.tpmLimit && + tpmLimitType == other.tpmLimitType && + userId == other.userId && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(aliases, allowedCacheControls, blocked, budgetDuration, budgetId, config, duration, enforcedParams, guardrails, key, keyAlias, maxBudget, maxParallelRequests, metadata, modelMaxBudget, modelRpmLimit, modelTpmLimit, models, permissions, rpmLimit, sendInviteEmail, softBudget, spend, tags, teamId, tpmLimit, userId, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + aliases, + allowedCacheControls, + allowedPassthroughRoutes, + allowedRoutes, + allowedVectorStoreIndexes, + autoRotate, + blocked, + budgetDuration, + budgetId, + config, + duration, + enforcedParams, + guardrails, + key, + keyAlias, + keyType, + maxBudget, + maxParallelRequests, + metadata, + modelMaxBudget, + modelRpmLimit, + modelTpmLimit, + models, + objectPermission, + organizationId, + permissions, + prompts, + rotationInterval, + routerSettings, + rpmLimit, + rpmLimitType, + sendInviteEmail, + softBudget, + spend, + tags, + teamId, + tpmLimit, + tpmLimitType, + userId, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "Body{aliases=$aliases, allowedCacheControls=$allowedCacheControls, blocked=$blocked, budgetDuration=$budgetDuration, budgetId=$budgetId, config=$config, duration=$duration, enforcedParams=$enforcedParams, guardrails=$guardrails, key=$key, keyAlias=$keyAlias, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelRpmLimit=$modelRpmLimit, modelTpmLimit=$modelTpmLimit, models=$models, permissions=$permissions, rpmLimit=$rpmLimit, sendInviteEmail=$sendInviteEmail, softBudget=$softBudget, spend=$spend, tags=$tags, teamId=$teamId, tpmLimit=$tpmLimit, userId=$userId, additionalProperties=$additionalProperties}" + "Body{aliases=$aliases, allowedCacheControls=$allowedCacheControls, allowedPassthroughRoutes=$allowedPassthroughRoutes, allowedRoutes=$allowedRoutes, allowedVectorStoreIndexes=$allowedVectorStoreIndexes, autoRotate=$autoRotate, blocked=$blocked, budgetDuration=$budgetDuration, budgetId=$budgetId, config=$config, duration=$duration, enforcedParams=$enforcedParams, guardrails=$guardrails, key=$key, keyAlias=$keyAlias, keyType=$keyType, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelRpmLimit=$modelRpmLimit, modelTpmLimit=$modelTpmLimit, models=$models, objectPermission=$objectPermission, organizationId=$organizationId, permissions=$permissions, prompts=$prompts, rotationInterval=$rotationInterval, routerSettings=$routerSettings, rpmLimit=$rpmLimit, rpmLimitType=$rpmLimitType, sendInviteEmail=$sendInviteEmail, softBudget=$softBudget, spend=$spend, tags=$tags, teamId=$teamId, tpmLimit=$tpmLimit, tpmLimitType=$tpmLimitType, userId=$userId, additionalProperties=$additionalProperties}" + } + + class Aliases + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Aliases]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Aliases]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aliases: Aliases) = apply { + additionalProperties = aliases.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Aliases]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Aliases = Aliases(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Aliases = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Aliases && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Aliases{additionalProperties=$additionalProperties}" + } + + class AllowedVectorStoreIndex + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val indexName: JsonField, + private val indexPermissions: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("index_name") + @ExcludeMissing + indexName: JsonField = JsonMissing.of(), + @JsonProperty("index_permissions") + @ExcludeMissing + indexPermissions: JsonField> = JsonMissing.of(), + ) : this(indexName, indexPermissions, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun indexName(): String = indexName.getRequired("index_name") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun indexPermissions(): List = + indexPermissions.getRequired("index_permissions") + + /** + * Returns the raw JSON value of [indexName]. + * + * Unlike [indexName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("index_name") @ExcludeMissing fun _indexName(): JsonField = indexName + + /** + * Returns the raw JSON value of [indexPermissions]. + * + * Unlike [indexPermissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("index_permissions") + @ExcludeMissing + fun _indexPermissions(): JsonField> = indexPermissions + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AllowedVectorStoreIndex]. + * + * The following fields are required: + * ```java + * .indexName() + * .indexPermissions() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AllowedVectorStoreIndex]. */ + class Builder internal constructor() { + + private var indexName: JsonField? = null + private var indexPermissions: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(allowedVectorStoreIndex: AllowedVectorStoreIndex) = apply { + indexName = allowedVectorStoreIndex.indexName + indexPermissions = + allowedVectorStoreIndex.indexPermissions.map { it.toMutableList() } + additionalProperties = allowedVectorStoreIndex.additionalProperties.toMutableMap() + } + + fun indexName(indexName: String) = indexName(JsonField.of(indexName)) + + /** + * Sets [Builder.indexName] to an arbitrary JSON value. + * + * You should usually call [Builder.indexName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun indexName(indexName: JsonField) = apply { this.indexName = indexName } + + fun indexPermissions(indexPermissions: List) = + indexPermissions(JsonField.of(indexPermissions)) + + /** + * Sets [Builder.indexPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.indexPermissions] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun indexPermissions(indexPermissions: JsonField>) = apply { + this.indexPermissions = indexPermissions.map { it.toMutableList() } + } + + /** + * Adds a single [IndexPermission] to [indexPermissions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addIndexPermission(indexPermission: IndexPermission) = apply { + indexPermissions = + (indexPermissions ?: JsonField.of(mutableListOf())).also { + checkKnown("indexPermissions", it).add(indexPermission) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AllowedVectorStoreIndex]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .indexName() + * .indexPermissions() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AllowedVectorStoreIndex = + AllowedVectorStoreIndex( + checkRequired("indexName", indexName), + checkRequired("indexPermissions", indexPermissions).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AllowedVectorStoreIndex = apply { + if (validated) { + return@apply + } + + indexName() + indexPermissions().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (indexName.asKnown().isPresent) 1 else 0) + + (indexPermissions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + class IndexPermission + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val READ = of("read") + + @JvmField val WRITE = of("write") + + @JvmStatic fun of(value: String) = IndexPermission(JsonField.of(value)) + } + + /** An enum containing [IndexPermission]'s known values. */ + enum class Known { + READ, + WRITE, + } + + /** + * An enum containing [IndexPermission]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [IndexPermission] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + READ, + WRITE, + /** + * An enum member indicating that [IndexPermission] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + READ -> Value.READ + WRITE -> Value.WRITE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + READ -> Known.READ + WRITE -> Known.WRITE + else -> throw HanzoInvalidDataException("Unknown IndexPermission: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + HanzoInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): IndexPermission = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is IndexPermission && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AllowedVectorStoreIndex && + indexName == other.indexName && + indexPermissions == other.indexPermissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(indexName, indexPermissions, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AllowedVectorStoreIndex{indexName=$indexName, indexPermissions=$indexPermissions, additionalProperties=$additionalProperties}" + } + + class Config + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Config]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Config]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(config: Config) = apply { + additionalProperties = config.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Config]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Config = Config(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Config = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Config && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Config{additionalProperties=$additionalProperties}" + } + + /** Enum for key types that determine what routes a key can access */ + class KeyType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LLM_API = of("llm_api") + + @JvmField val MANAGEMENT = of("management") + + @JvmField val READ_ONLY = of("read_only") + + @JvmField val DEFAULT = of("default") + + @JvmStatic fun of(value: String) = KeyType(JsonField.of(value)) + } + + /** An enum containing [KeyType]'s known values. */ + enum class Known { + LLM_API, + MANAGEMENT, + READ_ONLY, + DEFAULT, + } + + /** + * An enum containing [KeyType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [KeyType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LLM_API, + MANAGEMENT, + READ_ONLY, + DEFAULT, + /** An enum member indicating that [KeyType] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + LLM_API -> Value.LLM_API + MANAGEMENT -> Value.MANAGEMENT + READ_ONLY -> Value.READ_ONLY + DEFAULT -> Value.DEFAULT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + LLM_API -> Known.LLM_API + MANAGEMENT -> Known.MANAGEMENT + READ_ONLY -> Known.READ_ONLY + DEFAULT -> Known.DEFAULT + else -> throw HanzoInvalidDataException("Unknown KeyType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): KeyType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is KeyType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + class ModelMaxBudget + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelMaxBudget]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelMaxBudget]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelMaxBudget: ModelMaxBudget) = apply { + additionalProperties = modelMaxBudget.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelMaxBudget]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelMaxBudget = ModelMaxBudget(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelMaxBudget = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelMaxBudget && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelMaxBudget{additionalProperties=$additionalProperties}" + } + + class ModelRpmLimit + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelRpmLimit]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelRpmLimit]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelRpmLimit: ModelRpmLimit) = apply { + additionalProperties = modelRpmLimit.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelRpmLimit]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelRpmLimit = ModelRpmLimit(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelRpmLimit = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelRpmLimit && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelRpmLimit{additionalProperties=$additionalProperties}" + } + + class ModelTpmLimit + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelTpmLimit]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelTpmLimit]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelTpmLimit: ModelTpmLimit) = apply { + additionalProperties = modelTpmLimit.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelTpmLimit]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelTpmLimit = ModelTpmLimit(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelTpmLimit = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelTpmLimit && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelTpmLimit{additionalProperties=$additionalProperties}" + } + + class ObjectPermission + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val agentAccessGroups: JsonField>, + private val agents: JsonField>, + private val mcpAccessGroups: JsonField>, + private val mcpServers: JsonField>, + private val mcpToolPermissions: JsonField, + private val vectorStores: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("agent_access_groups") + @ExcludeMissing + agentAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("agents") + @ExcludeMissing + agents: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_access_groups") + @ExcludeMissing + mcpAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_servers") + @ExcludeMissing + mcpServers: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + mcpToolPermissions: JsonField = JsonMissing.of(), + @JsonProperty("vector_stores") + @ExcludeMissing + vectorStores: JsonField> = JsonMissing.of(), + ) : this( + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun agentAccessGroups(): Optional> = + agentAccessGroups.getOptional("agent_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun agents(): Optional> = agents.getOptional("agents") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpAccessGroups(): Optional> = + mcpAccessGroups.getOptional("mcp_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpServers(): Optional> = mcpServers.getOptional("mcp_servers") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpToolPermissions(): Optional = + mcpToolPermissions.getOptional("mcp_tool_permissions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun vectorStores(): Optional> = vectorStores.getOptional("vector_stores") + + /** + * Returns the raw JSON value of [agentAccessGroups]. + * + * Unlike [agentAccessGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("agent_access_groups") + @ExcludeMissing + fun _agentAccessGroups(): JsonField> = agentAccessGroups + + /** + * Returns the raw JSON value of [agents]. + * + * Unlike [agents], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("agents") @ExcludeMissing fun _agents(): JsonField> = agents + + /** + * Returns the raw JSON value of [mcpAccessGroups]. + * + * Unlike [mcpAccessGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("mcp_access_groups") + @ExcludeMissing + fun _mcpAccessGroups(): JsonField> = mcpAccessGroups + + /** + * Returns the raw JSON value of [mcpServers]. + * + * Unlike [mcpServers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("mcp_servers") + @ExcludeMissing + fun _mcpServers(): JsonField> = mcpServers + + /** + * Returns the raw JSON value of [mcpToolPermissions]. + * + * Unlike [mcpToolPermissions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + fun _mcpToolPermissions(): JsonField = mcpToolPermissions + + /** + * Returns the raw JSON value of [vectorStores]. + * + * Unlike [vectorStores], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("vector_stores") + @ExcludeMissing + fun _vectorStores(): JsonField> = vectorStores + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ObjectPermission]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ObjectPermission]. */ + class Builder internal constructor() { + + private var agentAccessGroups: JsonField>? = null + private var agents: JsonField>? = null + private var mcpAccessGroups: JsonField>? = null + private var mcpServers: JsonField>? = null + private var mcpToolPermissions: JsonField = JsonMissing.of() + private var vectorStores: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(objectPermission: ObjectPermission) = apply { + agentAccessGroups = objectPermission.agentAccessGroups.map { it.toMutableList() } + agents = objectPermission.agents.map { it.toMutableList() } + mcpAccessGroups = objectPermission.mcpAccessGroups.map { it.toMutableList() } + mcpServers = objectPermission.mcpServers.map { it.toMutableList() } + mcpToolPermissions = objectPermission.mcpToolPermissions + vectorStores = objectPermission.vectorStores.map { it.toMutableList() } + additionalProperties = objectPermission.additionalProperties.toMutableMap() + } + + fun agentAccessGroups(agentAccessGroups: List?) = + agentAccessGroups(JsonField.ofNullable(agentAccessGroups)) + + /** + * Alias for calling [Builder.agentAccessGroups] with `agentAccessGroups.orElse(null)`. + */ + fun agentAccessGroups(agentAccessGroups: Optional>) = + agentAccessGroups(agentAccessGroups.getOrNull()) + + /** + * Sets [Builder.agentAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.agentAccessGroups] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun agentAccessGroups(agentAccessGroups: JsonField>) = apply { + this.agentAccessGroups = agentAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agentAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgentAccessGroup(agentAccessGroup: String) = apply { + agentAccessGroups = + (agentAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("agentAccessGroups", it).add(agentAccessGroup) + } + } + + fun agents(agents: List?) = agents(JsonField.ofNullable(agents)) + + /** Alias for calling [Builder.agents] with `agents.orElse(null)`. */ + fun agents(agents: Optional>) = agents(agents.getOrNull()) + + /** + * Sets [Builder.agents] to an arbitrary JSON value. + * + * You should usually call [Builder.agents] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun agents(agents: JsonField>) = apply { + this.agents = agents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgent(agent: String) = apply { + agents = + (agents ?: JsonField.of(mutableListOf())).also { + checkKnown("agents", it).add(agent) + } + } + + fun mcpAccessGroups(mcpAccessGroups: List?) = + mcpAccessGroups(JsonField.ofNullable(mcpAccessGroups)) + + /** Alias for calling [Builder.mcpAccessGroups] with `mcpAccessGroups.orElse(null)`. */ + fun mcpAccessGroups(mcpAccessGroups: Optional>) = + mcpAccessGroups(mcpAccessGroups.getOrNull()) + + /** + * Sets [Builder.mcpAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpAccessGroups] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun mcpAccessGroups(mcpAccessGroups: JsonField>) = apply { + this.mcpAccessGroups = mcpAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpAccessGroup(mcpAccessGroup: String) = apply { + mcpAccessGroups = + (mcpAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpAccessGroups", it).add(mcpAccessGroup) + } + } + + fun mcpServers(mcpServers: List?) = mcpServers(JsonField.ofNullable(mcpServers)) + + /** Alias for calling [Builder.mcpServers] with `mcpServers.orElse(null)`. */ + fun mcpServers(mcpServers: Optional>) = mcpServers(mcpServers.getOrNull()) + + /** + * Sets [Builder.mcpServers] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpServers] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun mcpServers(mcpServers: JsonField>) = apply { + this.mcpServers = mcpServers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpServers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpServer(mcpServer: String) = apply { + mcpServers = + (mcpServers ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpServers", it).add(mcpServer) + } + } + + fun mcpToolPermissions(mcpToolPermissions: McpToolPermissions?) = + mcpToolPermissions(JsonField.ofNullable(mcpToolPermissions)) + + /** + * Alias for calling [Builder.mcpToolPermissions] with + * `mcpToolPermissions.orElse(null)`. + */ + fun mcpToolPermissions(mcpToolPermissions: Optional) = + mcpToolPermissions(mcpToolPermissions.getOrNull()) + + /** + * Sets [Builder.mcpToolPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpToolPermissions] with a well-typed + * [McpToolPermissions] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun mcpToolPermissions(mcpToolPermissions: JsonField) = apply { + this.mcpToolPermissions = mcpToolPermissions + } + + fun vectorStores(vectorStores: List?) = + vectorStores(JsonField.ofNullable(vectorStores)) + + /** Alias for calling [Builder.vectorStores] with `vectorStores.orElse(null)`. */ + fun vectorStores(vectorStores: Optional>) = + vectorStores(vectorStores.getOrNull()) + + /** + * Sets [Builder.vectorStores] to an arbitrary JSON value. + * + * You should usually call [Builder.vectorStores] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun vectorStores(vectorStores: JsonField>) = apply { + this.vectorStores = vectorStores.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [vectorStores]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addVectorStore(vectorStore: String) = apply { + vectorStores = + (vectorStores ?: JsonField.of(mutableListOf())).also { + checkKnown("vectorStores", it).add(vectorStore) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ObjectPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ObjectPermission = + ObjectPermission( + (agentAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (agents ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpServers ?: JsonMissing.of()).map { it.toImmutable() }, + mcpToolPermissions, + (vectorStores ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ObjectPermission = apply { + if (validated) { + return@apply + } + + agentAccessGroups() + agents() + mcpAccessGroups() + mcpServers() + mcpToolPermissions().ifPresent { it.validate() } + vectorStores() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (agentAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (agents.asKnown().getOrNull()?.size ?: 0) + + (mcpAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (mcpServers.asKnown().getOrNull()?.size ?: 0) + + (mcpToolPermissions.asKnown().getOrNull()?.validity() ?: 0) + + (vectorStores.asKnown().getOrNull()?.size ?: 0) + + class McpToolPermissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [McpToolPermissions]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [McpToolPermissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(mcpToolPermissions: McpToolPermissions) = apply { + additionalProperties = mcpToolPermissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [McpToolPermissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): McpToolPermissions = + McpToolPermissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): McpToolPermissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is McpToolPermissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "McpToolPermissions{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ObjectPermission && + agentAccessGroups == other.agentAccessGroups && + agents == other.agents && + mcpAccessGroups == other.mcpAccessGroups && + mcpServers == other.mcpServers && + mcpToolPermissions == other.mcpToolPermissions && + vectorStores == other.vectorStores && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ObjectPermission{agentAccessGroups=$agentAccessGroups, agents=$agents, mcpAccessGroups=$mcpAccessGroups, mcpServers=$mcpServers, mcpToolPermissions=$mcpToolPermissions, vectorStores=$vectorStores, additionalProperties=$additionalProperties}" + } + + class Permissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Permissions]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Permissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(permissions: Permissions) = apply { + additionalProperties = permissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Permissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Permissions = Permissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Permissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Permissions && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Permissions{additionalProperties=$additionalProperties}" + } + + /** Set of params that you can modify via `router.update_settings()`. */ + class RouterSettings + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val allowedFails: JsonField, + private val contextWindowFallbacks: JsonField>, + private val cooldownTime: JsonField, + private val fallbacks: JsonField>, + private val maxRetries: JsonField, + private val modelGroupAlias: JsonField, + private val modelGroupRetryPolicy: JsonField, + private val numRetries: JsonField, + private val retryAfter: JsonField, + private val routingStrategy: JsonField, + private val routingStrategyArgs: JsonField, + private val timeout: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("allowed_fails") + @ExcludeMissing + allowedFails: JsonField = JsonMissing.of(), + @JsonProperty("context_window_fallbacks") + @ExcludeMissing + contextWindowFallbacks: JsonField> = JsonMissing.of(), + @JsonProperty("cooldown_time") + @ExcludeMissing + cooldownTime: JsonField = JsonMissing.of(), + @JsonProperty("fallbacks") + @ExcludeMissing + fallbacks: JsonField> = JsonMissing.of(), + @JsonProperty("max_retries") + @ExcludeMissing + maxRetries: JsonField = JsonMissing.of(), + @JsonProperty("model_group_alias") + @ExcludeMissing + modelGroupAlias: JsonField = JsonMissing.of(), + @JsonProperty("model_group_retry_policy") + @ExcludeMissing + modelGroupRetryPolicy: JsonField = JsonMissing.of(), + @JsonProperty("num_retries") + @ExcludeMissing + numRetries: JsonField = JsonMissing.of(), + @JsonProperty("retry_after") + @ExcludeMissing + retryAfter: JsonField = JsonMissing.of(), + @JsonProperty("routing_strategy") + @ExcludeMissing + routingStrategy: JsonField = JsonMissing.of(), + @JsonProperty("routing_strategy_args") + @ExcludeMissing + routingStrategyArgs: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + ) : this( + allowedFails, + contextWindowFallbacks, + cooldownTime, + fallbacks, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedFails(): Optional = allowedFails.getOptional("allowed_fails") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun contextWindowFallbacks(): Optional> = + contextWindowFallbacks.getOptional("context_window_fallbacks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cooldownTime(): Optional = cooldownTime.getOptional("cooldown_time") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fallbacks(): Optional> = fallbacks.getOptional("fallbacks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxRetries(): Optional = maxRetries.getOptional("max_retries") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelGroupAlias(): Optional = + modelGroupAlias.getOptional("model_group_alias") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelGroupRetryPolicy(): Optional = + modelGroupRetryPolicy.getOptional("model_group_retry_policy") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun numRetries(): Optional = numRetries.getOptional("num_retries") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun retryAfter(): Optional = retryAfter.getOptional("retry_after") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routingStrategy(): Optional = routingStrategy.getOptional("routing_strategy") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routingStrategyArgs(): Optional = + routingStrategyArgs.getOptional("routing_strategy_args") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = timeout.getOptional("timeout") + + /** + * Returns the raw JSON value of [allowedFails]. + * + * Unlike [allowedFails], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("allowed_fails") + @ExcludeMissing + fun _allowedFails(): JsonField = allowedFails + + /** + * Returns the raw JSON value of [contextWindowFallbacks]. + * + * Unlike [contextWindowFallbacks], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("context_window_fallbacks") + @ExcludeMissing + fun _contextWindowFallbacks(): JsonField> = + contextWindowFallbacks + + /** + * Returns the raw JSON value of [cooldownTime]. + * + * Unlike [cooldownTime], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cooldown_time") + @ExcludeMissing + fun _cooldownTime(): JsonField = cooldownTime + + /** + * Returns the raw JSON value of [fallbacks]. + * + * Unlike [fallbacks], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fallbacks") + @ExcludeMissing + fun _fallbacks(): JsonField> = fallbacks + + /** + * Returns the raw JSON value of [maxRetries]. + * + * Unlike [maxRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("max_retries") @ExcludeMissing fun _maxRetries(): JsonField = maxRetries + + /** + * Returns the raw JSON value of [modelGroupAlias]. + * + * Unlike [modelGroupAlias], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("model_group_alias") + @ExcludeMissing + fun _modelGroupAlias(): JsonField = modelGroupAlias + + /** + * Returns the raw JSON value of [modelGroupRetryPolicy]. + * + * Unlike [modelGroupRetryPolicy], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("model_group_retry_policy") + @ExcludeMissing + fun _modelGroupRetryPolicy(): JsonField = modelGroupRetryPolicy + + /** + * Returns the raw JSON value of [numRetries]. + * + * Unlike [numRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("num_retries") @ExcludeMissing fun _numRetries(): JsonField = numRetries + + /** + * Returns the raw JSON value of [retryAfter]. + * + * Unlike [retryAfter], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("retry_after") + @ExcludeMissing + fun _retryAfter(): JsonField = retryAfter + + /** + * Returns the raw JSON value of [routingStrategy]. + * + * Unlike [routingStrategy], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("routing_strategy") + @ExcludeMissing + fun _routingStrategy(): JsonField = routingStrategy + + /** + * Returns the raw JSON value of [routingStrategyArgs]. + * + * Unlike [routingStrategyArgs], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("routing_strategy_args") + @ExcludeMissing + fun _routingStrategyArgs(): JsonField = routingStrategyArgs + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RouterSettings]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RouterSettings]. */ + class Builder internal constructor() { + + private var allowedFails: JsonField = JsonMissing.of() + private var contextWindowFallbacks: JsonField>? = + null + private var cooldownTime: JsonField = JsonMissing.of() + private var fallbacks: JsonField>? = null + private var maxRetries: JsonField = JsonMissing.of() + private var modelGroupAlias: JsonField = JsonMissing.of() + private var modelGroupRetryPolicy: JsonField = JsonMissing.of() + private var numRetries: JsonField = JsonMissing.of() + private var retryAfter: JsonField = JsonMissing.of() + private var routingStrategy: JsonField = JsonMissing.of() + private var routingStrategyArgs: JsonField = JsonMissing.of() + private var timeout: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(routerSettings: RouterSettings) = apply { + allowedFails = routerSettings.allowedFails + contextWindowFallbacks = + routerSettings.contextWindowFallbacks.map { it.toMutableList() } + cooldownTime = routerSettings.cooldownTime + fallbacks = routerSettings.fallbacks.map { it.toMutableList() } + maxRetries = routerSettings.maxRetries + modelGroupAlias = routerSettings.modelGroupAlias + modelGroupRetryPolicy = routerSettings.modelGroupRetryPolicy + numRetries = routerSettings.numRetries + retryAfter = routerSettings.retryAfter + routingStrategy = routerSettings.routingStrategy + routingStrategyArgs = routerSettings.routingStrategyArgs + timeout = routerSettings.timeout + additionalProperties = routerSettings.additionalProperties.toMutableMap() + } + + fun allowedFails(allowedFails: Long?) = allowedFails(JsonField.ofNullable(allowedFails)) + + /** + * Alias for [Builder.allowedFails]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun allowedFails(allowedFails: Long) = allowedFails(allowedFails as Long?) + + /** Alias for calling [Builder.allowedFails] with `allowedFails.orElse(null)`. */ + fun allowedFails(allowedFails: Optional) = allowedFails(allowedFails.getOrNull()) + + /** + * Sets [Builder.allowedFails] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedFails] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun allowedFails(allowedFails: JsonField) = apply { + this.allowedFails = allowedFails + } + + fun contextWindowFallbacks(contextWindowFallbacks: List?) = + contextWindowFallbacks(JsonField.ofNullable(contextWindowFallbacks)) + + /** + * Alias for calling [Builder.contextWindowFallbacks] with + * `contextWindowFallbacks.orElse(null)`. + */ + fun contextWindowFallbacks( + contextWindowFallbacks: Optional> + ) = contextWindowFallbacks(contextWindowFallbacks.getOrNull()) + + /** + * Sets [Builder.contextWindowFallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.contextWindowFallbacks] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun contextWindowFallbacks( + contextWindowFallbacks: JsonField> + ) = apply { + this.contextWindowFallbacks = contextWindowFallbacks.map { it.toMutableList() } + } + + /** + * Adds a single [ContextWindowFallback] to [contextWindowFallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addContextWindowFallback(contextWindowFallback: ContextWindowFallback) = apply { + contextWindowFallbacks = + (contextWindowFallbacks ?: JsonField.of(mutableListOf())).also { + checkKnown("contextWindowFallbacks", it).add(contextWindowFallback) + } + } + + fun cooldownTime(cooldownTime: Double?) = + cooldownTime(JsonField.ofNullable(cooldownTime)) + + /** + * Alias for [Builder.cooldownTime]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cooldownTime(cooldownTime: Double) = cooldownTime(cooldownTime as Double?) + + /** Alias for calling [Builder.cooldownTime] with `cooldownTime.orElse(null)`. */ + fun cooldownTime(cooldownTime: Optional) = + cooldownTime(cooldownTime.getOrNull()) + + /** + * Sets [Builder.cooldownTime] to an arbitrary JSON value. + * + * You should usually call [Builder.cooldownTime] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun cooldownTime(cooldownTime: JsonField) = apply { + this.cooldownTime = cooldownTime + } + + fun fallbacks(fallbacks: List?) = fallbacks(JsonField.ofNullable(fallbacks)) + + /** Alias for calling [Builder.fallbacks] with `fallbacks.orElse(null)`. */ + fun fallbacks(fallbacks: Optional>) = fallbacks(fallbacks.getOrNull()) + + /** + * Sets [Builder.fallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.fallbacks] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fallbacks(fallbacks: JsonField>) = apply { + this.fallbacks = fallbacks.map { it.toMutableList() } + } + + /** + * Adds a single [Fallback] to [fallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFallback(fallback: Fallback) = apply { + fallbacks = + (fallbacks ?: JsonField.of(mutableListOf())).also { + checkKnown("fallbacks", it).add(fallback) + } + } + + fun maxRetries(maxRetries: Long?) = maxRetries(JsonField.ofNullable(maxRetries)) + + /** + * Alias for [Builder.maxRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxRetries(maxRetries: Long) = maxRetries(maxRetries as Long?) + + /** Alias for calling [Builder.maxRetries] with `maxRetries.orElse(null)`. */ + fun maxRetries(maxRetries: Optional) = maxRetries(maxRetries.getOrNull()) + + /** + * Sets [Builder.maxRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.maxRetries] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxRetries(maxRetries: JsonField) = apply { this.maxRetries = maxRetries } + + fun modelGroupAlias(modelGroupAlias: ModelGroupAlias?) = + modelGroupAlias(JsonField.ofNullable(modelGroupAlias)) + + /** Alias for calling [Builder.modelGroupAlias] with `modelGroupAlias.orElse(null)`. */ + fun modelGroupAlias(modelGroupAlias: Optional) = + modelGroupAlias(modelGroupAlias.getOrNull()) + + /** + * Sets [Builder.modelGroupAlias] to an arbitrary JSON value. + * + * You should usually call [Builder.modelGroupAlias] with a well-typed [ModelGroupAlias] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun modelGroupAlias(modelGroupAlias: JsonField) = apply { + this.modelGroupAlias = modelGroupAlias + } + + fun modelGroupRetryPolicy(modelGroupRetryPolicy: ModelGroupRetryPolicy?) = + modelGroupRetryPolicy(JsonField.ofNullable(modelGroupRetryPolicy)) + + /** + * Alias for calling [Builder.modelGroupRetryPolicy] with + * `modelGroupRetryPolicy.orElse(null)`. + */ + fun modelGroupRetryPolicy(modelGroupRetryPolicy: Optional) = + modelGroupRetryPolicy(modelGroupRetryPolicy.getOrNull()) + + /** + * Sets [Builder.modelGroupRetryPolicy] to an arbitrary JSON value. + * + * You should usually call [Builder.modelGroupRetryPolicy] with a well-typed + * [ModelGroupRetryPolicy] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun modelGroupRetryPolicy(modelGroupRetryPolicy: JsonField) = + apply { + this.modelGroupRetryPolicy = modelGroupRetryPolicy + } + + fun numRetries(numRetries: Long?) = numRetries(JsonField.ofNullable(numRetries)) + + /** + * Alias for [Builder.numRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun numRetries(numRetries: Long) = numRetries(numRetries as Long?) + + /** Alias for calling [Builder.numRetries] with `numRetries.orElse(null)`. */ + fun numRetries(numRetries: Optional) = numRetries(numRetries.getOrNull()) + + /** + * Sets [Builder.numRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.numRetries] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun numRetries(numRetries: JsonField) = apply { this.numRetries = numRetries } + + fun retryAfter(retryAfter: Double?) = retryAfter(JsonField.ofNullable(retryAfter)) + + /** + * Alias for [Builder.retryAfter]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun retryAfter(retryAfter: Double) = retryAfter(retryAfter as Double?) + + /** Alias for calling [Builder.retryAfter] with `retryAfter.orElse(null)`. */ + fun retryAfter(retryAfter: Optional) = retryAfter(retryAfter.getOrNull()) + + /** + * Sets [Builder.retryAfter] to an arbitrary JSON value. + * + * You should usually call [Builder.retryAfter] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun retryAfter(retryAfter: JsonField) = apply { this.retryAfter = retryAfter } + + fun routingStrategy(routingStrategy: String?) = + routingStrategy(JsonField.ofNullable(routingStrategy)) + + /** Alias for calling [Builder.routingStrategy] with `routingStrategy.orElse(null)`. */ + fun routingStrategy(routingStrategy: Optional) = + routingStrategy(routingStrategy.getOrNull()) + + /** + * Sets [Builder.routingStrategy] to an arbitrary JSON value. + * + * You should usually call [Builder.routingStrategy] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun routingStrategy(routingStrategy: JsonField) = apply { + this.routingStrategy = routingStrategy + } + + fun routingStrategyArgs(routingStrategyArgs: RoutingStrategyArgs?) = + routingStrategyArgs(JsonField.ofNullable(routingStrategyArgs)) + + /** + * Alias for calling [Builder.routingStrategyArgs] with + * `routingStrategyArgs.orElse(null)`. + */ + fun routingStrategyArgs(routingStrategyArgs: Optional) = + routingStrategyArgs(routingStrategyArgs.getOrNull()) + + /** + * Sets [Builder.routingStrategyArgs] to an arbitrary JSON value. + * + * You should usually call [Builder.routingStrategyArgs] with a well-typed + * [RoutingStrategyArgs] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun routingStrategyArgs(routingStrategyArgs: JsonField) = apply { + this.routingStrategyArgs = routingStrategyArgs + } + + fun timeout(timeout: Double?) = timeout(JsonField.ofNullable(timeout)) + + /** + * Alias for [Builder.timeout]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun timeout(timeout: Double) = timeout(timeout as Double?) + + /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ + fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RouterSettings]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RouterSettings = + RouterSettings( + allowedFails, + (contextWindowFallbacks ?: JsonMissing.of()).map { it.toImmutable() }, + cooldownTime, + (fallbacks ?: JsonMissing.of()).map { it.toImmutable() }, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): RouterSettings = apply { + if (validated) { + return@apply + } + + allowedFails() + contextWindowFallbacks().ifPresent { it.forEach { it.validate() } } + cooldownTime() + fallbacks().ifPresent { it.forEach { it.validate() } } + maxRetries() + modelGroupAlias().ifPresent { it.validate() } + modelGroupRetryPolicy().ifPresent { it.validate() } + numRetries() + retryAfter() + routingStrategy() + routingStrategyArgs().ifPresent { it.validate() } + timeout() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (allowedFails.asKnown().isPresent) 1 else 0) + + (contextWindowFallbacks.asKnown().getOrNull()?.sumOf { it.validity().toInt() } + ?: 0) + + (if (cooldownTime.asKnown().isPresent) 1 else 0) + + (fallbacks.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (maxRetries.asKnown().isPresent) 1 else 0) + + (modelGroupAlias.asKnown().getOrNull()?.validity() ?: 0) + + (modelGroupRetryPolicy.asKnown().getOrNull()?.validity() ?: 0) + + (if (numRetries.asKnown().isPresent) 1 else 0) + + (if (retryAfter.asKnown().isPresent) 1 else 0) + + (if (routingStrategy.asKnown().isPresent) 1 else 0) + + (routingStrategyArgs.asKnown().getOrNull()?.validity() ?: 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + class ContextWindowFallback + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ContextWindowFallback]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ContextWindowFallback]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(contextWindowFallback: ContextWindowFallback) = apply { + additionalProperties = contextWindowFallback.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ContextWindowFallback]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ContextWindowFallback = + ContextWindowFallback(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ContextWindowFallback = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ContextWindowFallback && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ContextWindowFallback{additionalProperties=$additionalProperties}" + } + + class Fallback + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Fallback]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Fallback]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fallback: Fallback) = apply { + additionalProperties = fallback.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Fallback]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Fallback = Fallback(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Fallback = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Fallback && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Fallback{additionalProperties=$additionalProperties}" + } + + class ModelGroupAlias + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelGroupAlias]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelGroupAlias]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelGroupAlias: ModelGroupAlias) = apply { + additionalProperties = modelGroupAlias.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelGroupAlias]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelGroupAlias = ModelGroupAlias(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelGroupAlias = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelGroupAlias && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelGroupAlias{additionalProperties=$additionalProperties}" + } + + class ModelGroupRetryPolicy + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ModelGroupRetryPolicy]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelGroupRetryPolicy]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelGroupRetryPolicy: ModelGroupRetryPolicy) = apply { + additionalProperties = modelGroupRetryPolicy.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelGroupRetryPolicy]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelGroupRetryPolicy = + ModelGroupRetryPolicy(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelGroupRetryPolicy = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelGroupRetryPolicy && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ModelGroupRetryPolicy{additionalProperties=$additionalProperties}" + } + + class RoutingStrategyArgs + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RoutingStrategyArgs]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoutingStrategyArgs]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(routingStrategyArgs: RoutingStrategyArgs) = apply { + additionalProperties = routingStrategyArgs.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RoutingStrategyArgs]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RoutingStrategyArgs = + RoutingStrategyArgs(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): RoutingStrategyArgs = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RoutingStrategyArgs && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RoutingStrategyArgs{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RouterSettings && + allowedFails == other.allowedFails && + contextWindowFallbacks == other.contextWindowFallbacks && + cooldownTime == other.cooldownTime && + fallbacks == other.fallbacks && + maxRetries == other.maxRetries && + modelGroupAlias == other.modelGroupAlias && + modelGroupRetryPolicy == other.modelGroupRetryPolicy && + numRetries == other.numRetries && + retryAfter == other.retryAfter && + routingStrategy == other.routingStrategy && + routingStrategyArgs == other.routingStrategyArgs && + timeout == other.timeout && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + allowedFails, + contextWindowFallbacks, + cooldownTime, + fallbacks, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RouterSettings{allowedFails=$allowedFails, contextWindowFallbacks=$contextWindowFallbacks, cooldownTime=$cooldownTime, fallbacks=$fallbacks, maxRetries=$maxRetries, modelGroupAlias=$modelGroupAlias, modelGroupRetryPolicy=$modelGroupRetryPolicy, numRetries=$numRetries, retryAfter=$retryAfter, routingStrategy=$routingStrategy, routingStrategyArgs=$routingStrategyArgs, timeout=$timeout, additionalProperties=$additionalProperties}" + } + + class RpmLimitType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GUARANTEED_THROUGHPUT = of("guaranteed_throughput") + + @JvmField val BEST_EFFORT_THROUGHPUT = of("best_effort_throughput") + + @JvmField val DYNAMIC = of("dynamic") + + @JvmStatic fun of(value: String) = RpmLimitType(JsonField.of(value)) + } + + /** An enum containing [RpmLimitType]'s known values. */ + enum class Known { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + } + + /** + * An enum containing [RpmLimitType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [RpmLimitType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + /** + * An enum member indicating that [RpmLimitType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GUARANTEED_THROUGHPUT -> Value.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Value.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Value.DYNAMIC + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + GUARANTEED_THROUGHPUT -> Known.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Known.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Known.DYNAMIC + else -> throw HanzoInvalidDataException("Unknown RpmLimitType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): RpmLimitType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RpmLimitType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class TpmLimitType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GUARANTEED_THROUGHPUT = of("guaranteed_throughput") + + @JvmField val BEST_EFFORT_THROUGHPUT = of("best_effort_throughput") + + @JvmField val DYNAMIC = of("dynamic") + + @JvmStatic fun of(value: String) = TpmLimitType(JsonField.of(value)) + } + + /** An enum containing [TpmLimitType]'s known values. */ + enum class Known { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + } + + /** + * An enum containing [TpmLimitType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [TpmLimitType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + /** + * An enum member indicating that [TpmLimitType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GUARANTEED_THROUGHPUT -> Value.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Value.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Value.DYNAMIC + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + GUARANTEED_THROUGHPUT -> Known.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Known.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Known.DYNAMIC + else -> throw HanzoInvalidDataException("Unknown TpmLimitType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): TpmLimitType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TpmLimitType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() } override fun equals(other: Any?): Boolean { @@ -2040,11 +6876,16 @@ private constructor( return true } - return /* spotless:off */ other is KeyGenerateParams && llmChangedBy == other.llmChangedBy && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is KeyGenerateParams && + litellmChangedBy == other.litellmChangedBy && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(llmChangedBy, body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(litellmChangedBy, body, additionalHeaders, additionalQueryParams) override fun toString() = - "KeyGenerateParams{llmChangedBy=$llmChangedBy, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "KeyGenerateParams{litellmChangedBy=$litellmChangedBy, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyListParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyListParams.kt index 09dd6bce..74e75b2a 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyListParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyListParams.kt @@ -5,6 +5,7 @@ package ai.hanzo.api.models.key import ai.hanzo.api.core.Params import ai.hanzo.api.core.http.Headers import ai.hanzo.api.core.http.QueryParams +import ai.hanzo.api.core.toImmutable import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -12,29 +13,52 @@ import kotlin.jvm.optionals.getOrNull /** * List all keys for a given user / team / organization. * + * Parameters: expand: Optional[List[str]] - Expand related objects (e.g. 'user' to include user + * information) status: Optional[str] - Filter by status. Currently supports "deleted" to query + * deleted keys. + * * Returns: { "keys": List[str] or List[UserAPIKeyAuth], "total_count": int, "current_page": int, * "total_pages": int, } + * + * When expand includes "user", each key object will include a "user" field with the associated user + * object. Note: When expand=user is specified, full key objects are returned regardless of the + * return_full_object parameter. */ class KeyListParams private constructor( + private val expand: List?, + private val includeCreatedByKeys: Boolean?, private val includeTeamKeys: Boolean?, private val keyAlias: String?, + private val keyHash: String?, private val organizationId: String?, private val page: Long?, private val returnFullObject: Boolean?, private val size: Long?, + private val sortBy: String?, + private val sortOrder: String?, + private val status: String?, private val teamId: String?, private val userId: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { + /** Expand related objects (e.g. 'user') */ + fun expand(): Optional> = Optional.ofNullable(expand) + + /** Include keys created by the user */ + fun includeCreatedByKeys(): Optional = Optional.ofNullable(includeCreatedByKeys) + /** Include all keys for teams that user is an admin of. */ fun includeTeamKeys(): Optional = Optional.ofNullable(includeTeamKeys) /** Filter keys by key alias */ fun keyAlias(): Optional = Optional.ofNullable(keyAlias) + /** Filter keys by key hash */ + fun keyHash(): Optional = Optional.ofNullable(keyHash) + /** Filter keys by organization ID */ fun organizationId(): Optional = Optional.ofNullable(organizationId) @@ -47,14 +71,25 @@ private constructor( /** Page size */ fun size(): Optional = Optional.ofNullable(size) + /** Column to sort by (e.g. 'user_id', 'created_at', 'spend') */ + fun sortBy(): Optional = Optional.ofNullable(sortBy) + + /** Sort order ('asc' or 'desc') */ + fun sortOrder(): Optional = Optional.ofNullable(sortOrder) + + /** Filter by status (e.g. 'deleted') */ + fun status(): Optional = Optional.ofNullable(status) + /** Filter keys by team ID */ fun teamId(): Optional = Optional.ofNullable(teamId) /** Filter keys by user ID */ fun userId(): Optional = Optional.ofNullable(userId) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -70,12 +105,18 @@ private constructor( /** A builder for [KeyListParams]. */ class Builder internal constructor() { + private var expand: MutableList? = null + private var includeCreatedByKeys: Boolean? = null private var includeTeamKeys: Boolean? = null private var keyAlias: String? = null + private var keyHash: String? = null private var organizationId: String? = null private var page: Long? = null private var returnFullObject: Boolean? = null private var size: Long? = null + private var sortBy: String? = null + private var sortOrder: String? = null + private var status: String? = null private var teamId: String? = null private var userId: String? = null private var additionalHeaders: Headers.Builder = Headers.builder() @@ -83,18 +124,59 @@ private constructor( @JvmSynthetic internal fun from(keyListParams: KeyListParams) = apply { + expand = keyListParams.expand?.toMutableList() + includeCreatedByKeys = keyListParams.includeCreatedByKeys includeTeamKeys = keyListParams.includeTeamKeys keyAlias = keyListParams.keyAlias + keyHash = keyListParams.keyHash organizationId = keyListParams.organizationId page = keyListParams.page returnFullObject = keyListParams.returnFullObject size = keyListParams.size + sortBy = keyListParams.sortBy + sortOrder = keyListParams.sortOrder + status = keyListParams.status teamId = keyListParams.teamId userId = keyListParams.userId additionalHeaders = keyListParams.additionalHeaders.toBuilder() additionalQueryParams = keyListParams.additionalQueryParams.toBuilder() } + /** Expand related objects (e.g. 'user') */ + fun expand(expand: List?) = apply { this.expand = expand?.toMutableList() } + + /** Alias for calling [Builder.expand] with `expand.orElse(null)`. */ + fun expand(expand: Optional>) = expand(expand.getOrNull()) + + /** + * Adds a single [String] to [Builder.expand]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addExpand(expand: String) = apply { + this.expand = (this.expand ?: mutableListOf()).apply { add(expand) } + } + + /** Include keys created by the user */ + fun includeCreatedByKeys(includeCreatedByKeys: Boolean?) = apply { + this.includeCreatedByKeys = includeCreatedByKeys + } + + /** + * Alias for [Builder.includeCreatedByKeys]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun includeCreatedByKeys(includeCreatedByKeys: Boolean) = + includeCreatedByKeys(includeCreatedByKeys as Boolean?) + + /** + * Alias for calling [Builder.includeCreatedByKeys] with + * `includeCreatedByKeys.orElse(null)`. + */ + fun includeCreatedByKeys(includeCreatedByKeys: Optional) = + includeCreatedByKeys(includeCreatedByKeys.getOrNull()) + /** Include all keys for teams that user is an admin of. */ fun includeTeamKeys(includeTeamKeys: Boolean?) = apply { this.includeTeamKeys = includeTeamKeys @@ -117,6 +199,12 @@ private constructor( /** Alias for calling [Builder.keyAlias] with `keyAlias.orElse(null)`. */ fun keyAlias(keyAlias: Optional) = keyAlias(keyAlias.getOrNull()) + /** Filter keys by key hash */ + fun keyHash(keyHash: String?) = apply { this.keyHash = keyHash } + + /** Alias for calling [Builder.keyHash] with `keyHash.orElse(null)`. */ + fun keyHash(keyHash: Optional) = keyHash(keyHash.getOrNull()) + /** Filter keys by organization ID */ fun organizationId(organizationId: String?) = apply { this.organizationId = organizationId } @@ -167,6 +255,24 @@ private constructor( /** Alias for calling [Builder.size] with `size.orElse(null)`. */ fun size(size: Optional) = size(size.getOrNull()) + /** Column to sort by (e.g. 'user_id', 'created_at', 'spend') */ + fun sortBy(sortBy: String?) = apply { this.sortBy = sortBy } + + /** Alias for calling [Builder.sortBy] with `sortBy.orElse(null)`. */ + fun sortBy(sortBy: Optional) = sortBy(sortBy.getOrNull()) + + /** Sort order ('asc' or 'desc') */ + fun sortOrder(sortOrder: String?) = apply { this.sortOrder = sortOrder } + + /** Alias for calling [Builder.sortOrder] with `sortOrder.orElse(null)`. */ + fun sortOrder(sortOrder: Optional) = sortOrder(sortOrder.getOrNull()) + + /** Filter by status (e.g. 'deleted') */ + fun status(status: String?) = apply { this.status = status } + + /** Alias for calling [Builder.status] with `status.orElse(null)`. */ + fun status(status: Optional) = status(status.getOrNull()) + /** Filter keys by team ID */ fun teamId(teamId: String?) = apply { this.teamId = teamId } @@ -284,12 +390,18 @@ private constructor( */ fun build(): KeyListParams = KeyListParams( + expand?.toImmutable(), + includeCreatedByKeys, includeTeamKeys, keyAlias, + keyHash, organizationId, page, returnFullObject, size, + sortBy, + sortOrder, + status, teamId, userId, additionalHeaders.build(), @@ -302,12 +414,18 @@ private constructor( override fun _queryParams(): QueryParams = QueryParams.builder() .apply { + expand?.let { put("expand", it.joinToString(",")) } + includeCreatedByKeys?.let { put("include_created_by_keys", it.toString()) } includeTeamKeys?.let { put("include_team_keys", it.toString()) } keyAlias?.let { put("key_alias", it) } + keyHash?.let { put("key_hash", it) } organizationId?.let { put("organization_id", it) } page?.let { put("page", it.toString()) } returnFullObject?.let { put("return_full_object", it.toString()) } size?.let { put("size", it.toString()) } + sortBy?.let { put("sort_by", it) } + sortOrder?.let { put("sort_order", it) } + status?.let { put("status", it) } teamId?.let { put("team_id", it) } userId?.let { put("user_id", it) } putAll(additionalQueryParams) @@ -319,11 +437,45 @@ private constructor( return true } - return /* spotless:off */ other is KeyListParams && includeTeamKeys == other.includeTeamKeys && keyAlias == other.keyAlias && organizationId == other.organizationId && page == other.page && returnFullObject == other.returnFullObject && size == other.size && teamId == other.teamId && userId == other.userId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is KeyListParams && + expand == other.expand && + includeCreatedByKeys == other.includeCreatedByKeys && + includeTeamKeys == other.includeTeamKeys && + keyAlias == other.keyAlias && + keyHash == other.keyHash && + organizationId == other.organizationId && + page == other.page && + returnFullObject == other.returnFullObject && + size == other.size && + sortBy == other.sortBy && + sortOrder == other.sortOrder && + status == other.status && + teamId == other.teamId && + userId == other.userId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(includeTeamKeys, keyAlias, organizationId, page, returnFullObject, size, teamId, userId, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + expand, + includeCreatedByKeys, + includeTeamKeys, + keyAlias, + keyHash, + organizationId, + page, + returnFullObject, + size, + sortBy, + sortOrder, + status, + teamId, + userId, + additionalHeaders, + additionalQueryParams, + ) override fun toString() = - "KeyListParams{includeTeamKeys=$includeTeamKeys, keyAlias=$keyAlias, organizationId=$organizationId, page=$page, returnFullObject=$returnFullObject, size=$size, teamId=$teamId, userId=$userId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "KeyListParams{expand=$expand, includeCreatedByKeys=$includeCreatedByKeys, includeTeamKeys=$includeTeamKeys, keyAlias=$keyAlias, keyHash=$keyHash, organizationId=$organizationId, page=$page, returnFullObject=$returnFullObject, size=$size, sortBy=$sortBy, sortOrder=$sortOrder, status=$status, teamId=$teamId, userId=$userId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyListResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyListResponse.kt index 8f712e52..d44b5e37 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyListResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyListResponse.kt @@ -9,10 +9,13 @@ import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonField import ai.hanzo.api.core.JsonMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.core.allMaxBy import ai.hanzo.api.core.checkKnown +import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.getOrThrow import ai.hanzo.api.core.toImmutable import ai.hanzo.api.errors.HanzoInvalidDataException +import ai.hanzo.api.models.organization.UserRoles import ai.hanzo.api.models.team.Member import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter @@ -32,6 +35,7 @@ import java.util.Optional import kotlin.jvm.optionals.getOrNull class KeyListResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val currentPage: JsonField, private val keys: JsonField>, @@ -54,25 +58,25 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun currentPage(): Optional = Optional.ofNullable(currentPage.getNullable("current_page")) + fun currentPage(): Optional = currentPage.getOptional("current_page") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun keys(): Optional> = Optional.ofNullable(keys.getNullable("keys")) + fun keys(): Optional> = keys.getOptional("keys") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun totalCount(): Optional = Optional.ofNullable(totalCount.getNullable("total_count")) + fun totalCount(): Optional = totalCount.getOptional("total_count") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun totalPages(): Optional = Optional.ofNullable(totalPages.getNullable("total_pages")) + fun totalPages(): Optional = totalPages.getOptional("total_pages") /** * Returns the raw JSON value of [currentPage]. @@ -185,6 +189,13 @@ private constructor( fun addKey(userApiKeyAuth: Key.UserApiKeyAuth) = addKey(Key.ofUserApiKeyAuth(userApiKeyAuth)) + /** + * Alias for calling [addKey] with + * `Key.ofLiteLlmDeletedVerificationToken(liteLlmDeletedVerificationToken)`. + */ + fun addKey(liteLlmDeletedVerificationToken: Key.LiteLlmDeletedVerificationToken) = + addKey(Key.ofLiteLlmDeletedVerificationToken(liteLlmDeletedVerificationToken)) + fun totalCount(totalCount: Long?) = totalCount(JsonField.ofNullable(totalCount)) /** @@ -273,6 +284,26 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (currentPage.asKnown().isPresent) 1 else 0) + + (keys.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (totalCount.asKnown().isPresent) 1 else 0) + + (if (totalPages.asKnown().isPresent) 1 else 0) + /** Return the row in the db */ @JsonDeserialize(using = Key.Deserializer::class) @JsonSerialize(using = Key.Serializer::class) @@ -280,6 +311,7 @@ private constructor( private constructor( private val string: String? = null, private val userApiKeyAuth: UserApiKeyAuth? = null, + private val liteLlmDeletedVerificationToken: LiteLlmDeletedVerificationToken? = null, private val _json: JsonValue? = null, ) { @@ -288,24 +320,41 @@ private constructor( /** Return the row in the db */ fun userApiKeyAuth(): Optional = Optional.ofNullable(userApiKeyAuth) + /** + * Recording of deleted keys for audit purposes. Mirrors LiteLLM_VerificationToken plus + * metadata captured at deletion time. + */ + fun liteLlmDeletedVerificationToken(): Optional = + Optional.ofNullable(liteLlmDeletedVerificationToken) + fun isString(): Boolean = string != null fun isUserApiKeyAuth(): Boolean = userApiKeyAuth != null + fun isLiteLlmDeletedVerificationToken(): Boolean = liteLlmDeletedVerificationToken != null + fun asString(): String = string.getOrThrow("string") /** Return the row in the db */ fun asUserApiKeyAuth(): UserApiKeyAuth = userApiKeyAuth.getOrThrow("userApiKeyAuth") + /** + * Recording of deleted keys for audit purposes. Mirrors LiteLLM_VerificationToken plus + * metadata captured at deletion time. + */ + fun asLiteLlmDeletedVerificationToken(): LiteLlmDeletedVerificationToken = + liteLlmDeletedVerificationToken.getOrThrow("liteLlmDeletedVerificationToken") + fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) userApiKeyAuth != null -> visitor.visitUserApiKeyAuth(userApiKeyAuth) + liteLlmDeletedVerificationToken != null -> + visitor.visitLiteLlmDeletedVerificationToken(liteLlmDeletedVerificationToken) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -321,25 +370,68 @@ private constructor( override fun visitUserApiKeyAuth(userApiKeyAuth: UserApiKeyAuth) { userApiKeyAuth.validate() } + + override fun visitLiteLlmDeletedVerificationToken( + liteLlmDeletedVerificationToken: LiteLlmDeletedVerificationToken + ) { + liteLlmDeletedVerificationToken.validate() + } } ) validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitUserApiKeyAuth(userApiKeyAuth: UserApiKeyAuth) = + userApiKeyAuth.validity() + + override fun visitLiteLlmDeletedVerificationToken( + liteLlmDeletedVerificationToken: LiteLlmDeletedVerificationToken + ) = liteLlmDeletedVerificationToken.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Key && string == other.string && userApiKeyAuth == other.userApiKeyAuth /* spotless:on */ + return other is Key && + string == other.string && + userApiKeyAuth == other.userApiKeyAuth && + liteLlmDeletedVerificationToken == other.liteLlmDeletedVerificationToken } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, userApiKeyAuth) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(string, userApiKeyAuth, liteLlmDeletedVerificationToken) override fun toString(): String = when { string != null -> "Key{string=$string}" userApiKeyAuth != null -> "Key{userApiKeyAuth=$userApiKeyAuth}" + liteLlmDeletedVerificationToken != null -> + "Key{liteLlmDeletedVerificationToken=$liteLlmDeletedVerificationToken}" _json != null -> "Key{_unknown=$_json}" else -> throw IllegalStateException("Invalid Key") } @@ -352,6 +444,15 @@ private constructor( @JvmStatic fun ofUserApiKeyAuth(userApiKeyAuth: UserApiKeyAuth) = Key(userApiKeyAuth = userApiKeyAuth) + + /** + * Recording of deleted keys for audit purposes. Mirrors LiteLLM_VerificationToken plus + * metadata captured at deletion time. + */ + @JvmStatic + fun ofLiteLlmDeletedVerificationToken( + liteLlmDeletedVerificationToken: LiteLlmDeletedVerificationToken + ) = Key(liteLlmDeletedVerificationToken = liteLlmDeletedVerificationToken) } /** An interface that defines how to map each variant of [Key] to a value of type [T]. */ @@ -362,6 +463,14 @@ private constructor( /** Return the row in the db */ fun visitUserApiKeyAuth(userApiKeyAuth: UserApiKeyAuth): T + /** + * Recording of deleted keys for audit purposes. Mirrors LiteLLM_VerificationToken plus + * metadata captured at deletion time. + */ + fun visitLiteLlmDeletedVerificationToken( + liteLlmDeletedVerificationToken: LiteLlmDeletedVerificationToken + ): T + /** * Maps an unknown variant of [Key] to a value of type [T]. * @@ -381,15 +490,30 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Key { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return Key(string = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Key(userApiKeyAuth = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { Key(liteLlmDeletedVerificationToken = it, _json = json) }, + tryDeserialize(node, jacksonTypeRef())?.let { + Key(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with + // all the possible variants (e.g. deserializing from boolean). + 0 -> Key(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely + // valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Key(userApiKeyAuth = it, _json = json) - } - - return Key(_json = json) } } @@ -403,6 +527,8 @@ private constructor( when { value.string != null -> generator.writeObject(value.string) value.userApiKeyAuth != null -> generator.writeObject(value.userApiKeyAuth) + value.liteLlmDeletedVerificationToken != null -> + generator.writeObject(value.liteLlmDeletedVerificationToken) value._json != null -> generator.writeObject(value._json) else -> throw IllegalStateException("Invalid Key") } @@ -411,16 +537,19 @@ private constructor( /** Return the row in the db */ class UserApiKeyAuth + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val token: JsonField, - private val aliases: JsonValue, + private val aliases: JsonField, private val allowedCacheControls: JsonField>, private val allowedModelRegion: JsonField, + private val allowedRoutes: JsonField>, private val apiKey: JsonField, + private val autoRotate: JsonField, private val blocked: JsonField, private val budgetDuration: JsonField, private val budgetResetAt: JsonField, - private val config: JsonValue, + private val config: JsonField, private val createdAt: JsonField, private val createdBy: JsonField, private val endUserId: JsonField, @@ -430,17 +559,29 @@ private constructor( private val expires: JsonField, private val keyAlias: JsonField, private val keyName: JsonField, + private val keyRotationAt: JsonField, private val lastRefreshedAt: JsonField, - private val llmBudgetTable: JsonValue, + private val lastRotationAt: JsonField, + private val litellmBudgetTable: JsonField, private val maxBudget: JsonField, private val maxParallelRequests: JsonField, - private val metadata: JsonValue, - private val modelMaxBudget: JsonValue, - private val modelSpend: JsonValue, + private val metadata: JsonField, + private val modelMaxBudget: JsonField, + private val modelSpend: JsonField, private val models: JsonField>, + private val objectPermission: JsonField, + private val objectPermissionId: JsonField, private val orgId: JsonField, + private val organizationMaxBudget: JsonField, + private val organizationMetadata: JsonField, + private val organizationRpmLimit: JsonField, + private val organizationTpmLimit: JsonField, private val parentOtelSpan: JsonValue, - private val permissions: JsonValue, + private val permissions: JsonField, + private val requestRoute: JsonField, + private val rotationCount: JsonField, + private val rotationInterval: JsonField, + private val routerSettings: JsonField, private val rpmLimit: JsonField, private val rpmLimitPerModel: JsonField, private val softBudget: JsonField, @@ -451,10 +592,13 @@ private constructor( private val teamId: JsonField, private val teamMaxBudget: JsonField, private val teamMember: JsonField, + private val teamMemberRpmLimit: JsonField, private val teamMemberSpend: JsonField, - private val teamMetadata: JsonValue, - private val teamModelAliases: JsonValue, + private val teamMemberTpmLimit: JsonField, + private val teamMetadata: JsonField, + private val teamModelAliases: JsonField, private val teamModels: JsonField>, + private val teamObjectPermissionId: JsonField, private val teamRpmLimit: JsonField, private val teamSpend: JsonField, private val teamTpmLimit: JsonField, @@ -462,10 +606,13 @@ private constructor( private val tpmLimitPerModel: JsonField, private val updatedAt: JsonField, private val updatedBy: JsonField, + private val user: JsonValue, private val userEmail: JsonField, private val userId: JsonField, - private val userRole: JsonField, + private val userMaxBudget: JsonField, + private val userRole: JsonField, private val userRpmLimit: JsonField, + private val userSpend: JsonField, private val userTpmLimit: JsonField, private val additionalProperties: MutableMap, ) { @@ -473,16 +620,24 @@ private constructor( @JsonCreator private constructor( @JsonProperty("token") @ExcludeMissing token: JsonField = JsonMissing.of(), - @JsonProperty("aliases") @ExcludeMissing aliases: JsonValue = JsonMissing.of(), + @JsonProperty("aliases") + @ExcludeMissing + aliases: JsonField = JsonMissing.of(), @JsonProperty("allowed_cache_controls") @ExcludeMissing allowedCacheControls: JsonField> = JsonMissing.of(), @JsonProperty("allowed_model_region") @ExcludeMissing allowedModelRegion: JsonField = JsonMissing.of(), + @JsonProperty("allowed_routes") + @ExcludeMissing + allowedRoutes: JsonField> = JsonMissing.of(), @JsonProperty("api_key") @ExcludeMissing apiKey: JsonField = JsonMissing.of(), + @JsonProperty("auto_rotate") + @ExcludeMissing + autoRotate: JsonField = JsonMissing.of(), @JsonProperty("blocked") @ExcludeMissing blocked: JsonField = JsonMissing.of(), @@ -492,7 +647,9 @@ private constructor( @JsonProperty("budget_reset_at") @ExcludeMissing budgetResetAt: JsonField = JsonMissing.of(), - @JsonProperty("config") @ExcludeMissing config: JsonValue = JsonMissing.of(), + @JsonProperty("config") + @ExcludeMissing + config: JsonField = JsonMissing.of(), @JsonProperty("created_at") @ExcludeMissing createdAt: JsonField = JsonMissing.of(), @@ -520,35 +677,73 @@ private constructor( @JsonProperty("key_name") @ExcludeMissing keyName: JsonField = JsonMissing.of(), + @JsonProperty("key_rotation_at") + @ExcludeMissing + keyRotationAt: JsonField = JsonMissing.of(), @JsonProperty("last_refreshed_at") @ExcludeMissing lastRefreshedAt: JsonField = JsonMissing.of(), - @JsonProperty("llm_budget_table") + @JsonProperty("last_rotation_at") @ExcludeMissing - llmBudgetTable: JsonValue = JsonMissing.of(), + lastRotationAt: JsonField = JsonMissing.of(), + @JsonProperty("litellm_budget_table") + @ExcludeMissing + litellmBudgetTable: JsonField = JsonMissing.of(), @JsonProperty("max_budget") @ExcludeMissing maxBudget: JsonField = JsonMissing.of(), @JsonProperty("max_parallel_requests") @ExcludeMissing maxParallelRequests: JsonField = JsonMissing.of(), - @JsonProperty("metadata") @ExcludeMissing metadata: JsonValue = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), @JsonProperty("model_max_budget") @ExcludeMissing - modelMaxBudget: JsonValue = JsonMissing.of(), + modelMaxBudget: JsonField = JsonMissing.of(), @JsonProperty("model_spend") @ExcludeMissing - modelSpend: JsonValue = JsonMissing.of(), + modelSpend: JsonField = JsonMissing.of(), @JsonProperty("models") @ExcludeMissing models: JsonField> = JsonMissing.of(), + @JsonProperty("object_permission") + @ExcludeMissing + objectPermission: JsonField = JsonMissing.of(), + @JsonProperty("object_permission_id") + @ExcludeMissing + objectPermissionId: JsonField = JsonMissing.of(), @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("organization_max_budget") + @ExcludeMissing + organizationMaxBudget: JsonField = JsonMissing.of(), + @JsonProperty("organization_metadata") + @ExcludeMissing + organizationMetadata: JsonField = JsonMissing.of(), + @JsonProperty("organization_rpm_limit") + @ExcludeMissing + organizationRpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("organization_tpm_limit") + @ExcludeMissing + organizationTpmLimit: JsonField = JsonMissing.of(), @JsonProperty("parent_otel_span") @ExcludeMissing parentOtelSpan: JsonValue = JsonMissing.of(), @JsonProperty("permissions") @ExcludeMissing - permissions: JsonValue = JsonMissing.of(), + permissions: JsonField = JsonMissing.of(), + @JsonProperty("request_route") + @ExcludeMissing + requestRoute: JsonField = JsonMissing.of(), + @JsonProperty("rotation_count") + @ExcludeMissing + rotationCount: JsonField = JsonMissing.of(), + @JsonProperty("rotation_interval") + @ExcludeMissing + rotationInterval: JsonField = JsonMissing.of(), + @JsonProperty("router_settings") + @ExcludeMissing + routerSettings: JsonField = JsonMissing.of(), @JsonProperty("rpm_limit") @ExcludeMissing rpmLimit: JsonField = JsonMissing.of(), @@ -577,18 +772,27 @@ private constructor( @JsonProperty("team_member") @ExcludeMissing teamMember: JsonField = JsonMissing.of(), + @JsonProperty("team_member_rpm_limit") + @ExcludeMissing + teamMemberRpmLimit: JsonField = JsonMissing.of(), @JsonProperty("team_member_spend") @ExcludeMissing teamMemberSpend: JsonField = JsonMissing.of(), + @JsonProperty("team_member_tpm_limit") + @ExcludeMissing + teamMemberTpmLimit: JsonField = JsonMissing.of(), @JsonProperty("team_metadata") @ExcludeMissing - teamMetadata: JsonValue = JsonMissing.of(), + teamMetadata: JsonField = JsonMissing.of(), @JsonProperty("team_model_aliases") @ExcludeMissing - teamModelAliases: JsonValue = JsonMissing.of(), + teamModelAliases: JsonField = JsonMissing.of(), @JsonProperty("team_models") @ExcludeMissing teamModels: JsonField> = JsonMissing.of(), + @JsonProperty("team_object_permission_id") + @ExcludeMissing + teamObjectPermissionId: JsonField = JsonMissing.of(), @JsonProperty("team_rpm_limit") @ExcludeMissing teamRpmLimit: JsonField = JsonMissing.of(), @@ -610,18 +814,25 @@ private constructor( @JsonProperty("updated_by") @ExcludeMissing updatedBy: JsonField = JsonMissing.of(), + @JsonProperty("user") @ExcludeMissing user: JsonValue = JsonMissing.of(), @JsonProperty("user_email") @ExcludeMissing userEmail: JsonField = JsonMissing.of(), @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + @JsonProperty("user_max_budget") + @ExcludeMissing + userMaxBudget: JsonField = JsonMissing.of(), @JsonProperty("user_role") @ExcludeMissing - userRole: JsonField = JsonMissing.of(), + userRole: JsonField = JsonMissing.of(), @JsonProperty("user_rpm_limit") @ExcludeMissing userRpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("user_spend") + @ExcludeMissing + userSpend: JsonField = JsonMissing.of(), @JsonProperty("user_tpm_limit") @ExcludeMissing userTpmLimit: JsonField = JsonMissing.of(), @@ -630,7 +841,9 @@ private constructor( aliases, allowedCacheControls, allowedModelRegion, + allowedRoutes, apiKey, + autoRotate, blocked, budgetDuration, budgetResetAt, @@ -644,17 +857,29 @@ private constructor( expires, keyAlias, keyName, + keyRotationAt, lastRefreshedAt, - llmBudgetTable, + lastRotationAt, + litellmBudgetTable, maxBudget, maxParallelRequests, metadata, modelMaxBudget, modelSpend, models, + objectPermission, + objectPermissionId, orgId, + organizationMaxBudget, + organizationMetadata, + organizationRpmLimit, + organizationTpmLimit, parentOtelSpan, permissions, + requestRoute, + rotationCount, + rotationInterval, + routerSettings, rpmLimit, rpmLimitPerModel, softBudget, @@ -665,10 +890,13 @@ private constructor( teamId, teamMaxBudget, teamMember, + teamMemberRpmLimit, teamMemberSpend, + teamMemberTpmLimit, teamMetadata, teamModelAliases, teamModels, + teamObjectPermissionId, teamRpmLimit, teamSpend, teamTpmLimit, @@ -676,10 +904,13 @@ private constructor( tpmLimitPerModel, updatedAt, updatedBy, + user, userEmail, userId, + userMaxBudget, userRole, userRpmLimit, + userSpend, userTpmLimit, mutableMapOf(), ) @@ -688,314 +919,466 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun token(): Optional = Optional.ofNullable(token.getNullable("token")) + fun token(): Optional = token.getOptional("token") - @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonValue = aliases + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun aliases(): Optional = aliases.getOptional("aliases") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun allowedCacheControls(): Optional> = - Optional.ofNullable(allowedCacheControls.getNullable("allowed_cache_controls")) + allowedCacheControls.getOptional("allowed_cache_controls") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun allowedModelRegion(): Optional = - Optional.ofNullable(allowedModelRegion.getNullable("allowed_model_region")) + allowedModelRegion.getOptional("allowed_model_region") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun allowedRoutes(): Optional> = + allowedRoutes.getOptional("allowed_routes") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun apiKey(): Optional = apiKey.getOptional("api_key") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun apiKey(): Optional = Optional.ofNullable(apiKey.getNullable("api_key")) + fun autoRotate(): Optional = autoRotate.getOptional("auto_rotate") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun blocked(): Optional = Optional.ofNullable(blocked.getNullable("blocked")) + fun blocked(): Optional = blocked.getOptional("blocked") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun budgetDuration(): Optional = - Optional.ofNullable(budgetDuration.getNullable("budget_duration")) + fun budgetDuration(): Optional = budgetDuration.getOptional("budget_duration") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun budgetResetAt(): Optional = - Optional.ofNullable(budgetResetAt.getNullable("budget_reset_at")) + budgetResetAt.getOptional("budget_reset_at") - @JsonProperty("config") @ExcludeMissing fun _config(): JsonValue = config + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun config(): Optional = config.getOptional("config") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun createdAt(): Optional = - Optional.ofNullable(createdAt.getNullable("created_at")) + fun createdAt(): Optional = createdAt.getOptional("created_at") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun createdBy(): Optional = - Optional.ofNullable(createdBy.getNullable("created_by")) + fun createdBy(): Optional = createdBy.getOptional("created_by") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun endUserId(): Optional = - Optional.ofNullable(endUserId.getNullable("end_user_id")) + fun endUserId(): Optional = endUserId.getOptional("end_user_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun endUserMaxBudget(): Optional = - Optional.ofNullable(endUserMaxBudget.getNullable("end_user_max_budget")) + endUserMaxBudget.getOptional("end_user_max_budget") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun endUserRpmLimit(): Optional = - Optional.ofNullable(endUserRpmLimit.getNullable("end_user_rpm_limit")) + endUserRpmLimit.getOptional("end_user_rpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun endUserTpmLimit(): Optional = - Optional.ofNullable(endUserTpmLimit.getNullable("end_user_tpm_limit")) + endUserTpmLimit.getOptional("end_user_tpm_limit") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun expires(): Optional = expires.getOptional("expires") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun expires(): Optional = Optional.ofNullable(expires.getNullable("expires")) + fun keyAlias(): Optional = keyAlias.getOptional("key_alias") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun keyAlias(): Optional = - Optional.ofNullable(keyAlias.getNullable("key_alias")) + fun keyName(): Optional = keyName.getOptional("key_name") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun keyName(): Optional = Optional.ofNullable(keyName.getNullable("key_name")) + fun keyRotationAt(): Optional = + keyRotationAt.getOptional("key_rotation_at") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun lastRefreshedAt(): Optional = - Optional.ofNullable(lastRefreshedAt.getNullable("last_refreshed_at")) + lastRefreshedAt.getOptional("last_refreshed_at") - @JsonProperty("llm_budget_table") - @ExcludeMissing - fun _llmBudgetTable(): JsonValue = llmBudgetTable + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun lastRotationAt(): Optional = + lastRotationAt.getOptional("last_rotation_at") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun litellmBudgetTable(): Optional = + litellmBudgetTable.getOptional("litellm_budget_table") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun maxBudget(): Optional = - Optional.ofNullable(maxBudget.getNullable("max_budget")) + fun maxBudget(): Optional = maxBudget.getOptional("max_budget") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun maxParallelRequests(): Optional = - Optional.ofNullable(maxParallelRequests.getNullable("max_parallel_requests")) + maxParallelRequests.getOptional("max_parallel_requests") - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonValue = metadata + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") - @JsonProperty("model_max_budget") - @ExcludeMissing - fun _modelMaxBudget(): JsonValue = modelMaxBudget + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun modelMaxBudget(): Optional = + modelMaxBudget.getOptional("model_max_budget") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun modelSpend(): Optional = modelSpend.getOptional("model_spend") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun models(): Optional> = models.getOptional("models") + + /** + * Represents a LiteLLM_ObjectPermissionTable record + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun objectPermission(): Optional = + objectPermission.getOptional("object_permission") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun objectPermissionId(): Optional = + objectPermissionId.getOptional("object_permission_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun orgId(): Optional = orgId.getOptional("org_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun organizationMaxBudget(): Optional = + organizationMaxBudget.getOptional("organization_max_budget") - @JsonProperty("model_spend") @ExcludeMissing fun _modelSpend(): JsonValue = modelSpend + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun organizationMetadata(): Optional = + organizationMetadata.getOptional("organization_metadata") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun models(): Optional> = - Optional.ofNullable(models.getNullable("models")) + fun organizationRpmLimit(): Optional = + organizationRpmLimit.getOptional("organization_rpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun orgId(): Optional = Optional.ofNullable(orgId.getNullable("org_id")) + fun organizationTpmLimit(): Optional = + organizationTpmLimit.getOptional("organization_tpm_limit") + /** + * This arbitrary value can be deserialized into a custom type using the `convert` + * method: + * ```java + * MyClass myObject = userApiKeyAuth.parentOtelSpan().convert(MyClass.class); + * ``` + */ @JsonProperty("parent_otel_span") @ExcludeMissing fun _parentOtelSpan(): JsonValue = parentOtelSpan - @JsonProperty("permissions") @ExcludeMissing fun _permissions(): JsonValue = permissions + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun permissions(): Optional = permissions.getOptional("permissions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestRoute(): Optional = requestRoute.getOptional("request_route") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun rotationCount(): Optional = rotationCount.getOptional("rotation_count") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun rotationInterval(): Optional = + rotationInterval.getOptional("rotation_interval") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun routerSettings(): Optional = + routerSettings.getOptional("router_settings") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun rpmLimit(): Optional = Optional.ofNullable(rpmLimit.getNullable("rpm_limit")) + fun rpmLimit(): Optional = rpmLimit.getOptional("rpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun rpmLimitPerModel(): Optional = - Optional.ofNullable(rpmLimitPerModel.getNullable("rpm_limit_per_model")) + rpmLimitPerModel.getOptional("rpm_limit_per_model") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun softBudget(): Optional = - Optional.ofNullable(softBudget.getNullable("soft_budget")) + fun softBudget(): Optional = softBudget.getOptional("soft_budget") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun softBudgetCooldown(): Optional = - Optional.ofNullable(softBudgetCooldown.getNullable("soft_budget_cooldown")) + softBudgetCooldown.getOptional("soft_budget_cooldown") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun spend(): Optional = spend.getOptional("spend") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun spend(): Optional = Optional.ofNullable(spend.getNullable("spend")) + fun teamAlias(): Optional = teamAlias.getOptional("team_alias") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun teamAlias(): Optional = - Optional.ofNullable(teamAlias.getNullable("team_alias")) + fun teamBlocked(): Optional = teamBlocked.getOptional("team_blocked") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun teamBlocked(): Optional = - Optional.ofNullable(teamBlocked.getNullable("team_blocked")) + fun teamId(): Optional = teamId.getOptional("team_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun teamId(): Optional = Optional.ofNullable(teamId.getNullable("team_id")) + fun teamMaxBudget(): Optional = teamMaxBudget.getOptional("team_max_budget") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun teamMaxBudget(): Optional = - Optional.ofNullable(teamMaxBudget.getNullable("team_max_budget")) + fun teamMember(): Optional = teamMember.getOptional("team_member") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun teamMember(): Optional = - Optional.ofNullable(teamMember.getNullable("team_member")) + fun teamMemberRpmLimit(): Optional = + teamMemberRpmLimit.getOptional("team_member_rpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun teamMemberSpend(): Optional = - Optional.ofNullable(teamMemberSpend.getNullable("team_member_spend")) + teamMemberSpend.getOptional("team_member_spend") - @JsonProperty("team_metadata") - @ExcludeMissing - fun _teamMetadata(): JsonValue = teamMetadata + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun teamMemberTpmLimit(): Optional = + teamMemberTpmLimit.getOptional("team_member_tpm_limit") - @JsonProperty("team_model_aliases") - @ExcludeMissing - fun _teamModelAliases(): JsonValue = teamModelAliases + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun teamMetadata(): Optional = teamMetadata.getOptional("team_metadata") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun teamModelAliases(): Optional = + teamModelAliases.getOptional("team_model_aliases") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun teamModels(): Optional> = teamModels.getOptional("team_models") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun teamModels(): Optional> = - Optional.ofNullable(teamModels.getNullable("team_models")) + fun teamObjectPermissionId(): Optional = + teamObjectPermissionId.getOptional("team_object_permission_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun teamRpmLimit(): Optional = - Optional.ofNullable(teamRpmLimit.getNullable("team_rpm_limit")) + fun teamRpmLimit(): Optional = teamRpmLimit.getOptional("team_rpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun teamSpend(): Optional = - Optional.ofNullable(teamSpend.getNullable("team_spend")) + fun teamSpend(): Optional = teamSpend.getOptional("team_spend") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun teamTpmLimit(): Optional = - Optional.ofNullable(teamTpmLimit.getNullable("team_tpm_limit")) + fun teamTpmLimit(): Optional = teamTpmLimit.getOptional("team_tpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun tpmLimit(): Optional = Optional.ofNullable(tpmLimit.getNullable("tpm_limit")) + fun tpmLimit(): Optional = tpmLimit.getOptional("tpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ fun tpmLimitPerModel(): Optional = - Optional.ofNullable(tpmLimitPerModel.getNullable("tpm_limit_per_model")) + tpmLimitPerModel.getOptional("tpm_limit_per_model") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun updatedAt(): Optional = - Optional.ofNullable(updatedAt.getNullable("updated_at")) + fun updatedBy(): Optional = updatedBy.getOptional("updated_by") + + /** + * This arbitrary value can be deserialized into a custom type using the `convert` + * method: + * ```java + * MyClass myObject = userApiKeyAuth.user().convert(MyClass.class); + * ``` + */ + @JsonProperty("user") @ExcludeMissing fun _user(): JsonValue = user /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun updatedBy(): Optional = - Optional.ofNullable(updatedBy.getNullable("updated_by")) + fun userEmail(): Optional = userEmail.getOptional("user_email") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun userEmail(): Optional = - Optional.ofNullable(userEmail.getNullable("user_email")) + fun userId(): Optional = userId.getOptional("user_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) + fun userMaxBudget(): Optional = userMaxBudget.getOptional("user_max_budget") /** * Admin Roles: PROXY_ADMIN: admin over the platform PROXY_ADMIN_VIEW_ONLY: can login, @@ -1013,22 +1396,25 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun userRole(): Optional = - Optional.ofNullable(userRole.getNullable("user_role")) + fun userRole(): Optional = userRole.getOptional("user_role") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun userRpmLimit(): Optional = userRpmLimit.getOptional("user_rpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun userRpmLimit(): Optional = - Optional.ofNullable(userRpmLimit.getNullable("user_rpm_limit")) + fun userSpend(): Optional = userSpend.getOptional("user_spend") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if * the server responded with an unexpected value). */ - fun userTpmLimit(): Optional = - Optional.ofNullable(userTpmLimit.getNullable("user_tpm_limit")) + fun userTpmLimit(): Optional = userTpmLimit.getOptional("user_tpm_limit") /** * Returns the raw JSON value of [token]. @@ -1037,6 +1423,13 @@ private constructor( */ @JsonProperty("token") @ExcludeMissing fun _token(): JsonField = token + /** + * Returns the raw JSON value of [aliases]. + * + * Unlike [aliases], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonField = aliases + /** * Returns the raw JSON value of [allowedCacheControls]. * @@ -1057,6 +1450,16 @@ private constructor( @ExcludeMissing fun _allowedModelRegion(): JsonField = allowedModelRegion + /** + * Returns the raw JSON value of [allowedRoutes]. + * + * Unlike [allowedRoutes], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("allowed_routes") + @ExcludeMissing + fun _allowedRoutes(): JsonField> = allowedRoutes + /** * Returns the raw JSON value of [apiKey]. * @@ -1064,6 +1467,16 @@ private constructor( */ @JsonProperty("api_key") @ExcludeMissing fun _apiKey(): JsonField = apiKey + /** + * Returns the raw JSON value of [autoRotate]. + * + * Unlike [autoRotate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auto_rotate") + @ExcludeMissing + fun _autoRotate(): JsonField = autoRotate + /** * Returns the raw JSON value of [blocked]. * @@ -1091,6 +1504,13 @@ private constructor( @ExcludeMissing fun _budgetResetAt(): JsonField = budgetResetAt + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config") @ExcludeMissing fun _config(): JsonField = config + /** * Returns the raw JSON value of [createdAt]. * @@ -1173,6 +1593,16 @@ private constructor( */ @JsonProperty("key_name") @ExcludeMissing fun _keyName(): JsonField = keyName + /** + * Returns the raw JSON value of [keyRotationAt]. + * + * Unlike [keyRotationAt], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("key_rotation_at") + @ExcludeMissing + fun _keyRotationAt(): JsonField = keyRotationAt + /** * Returns the raw JSON value of [lastRefreshedAt]. * @@ -1183,6 +1613,26 @@ private constructor( @ExcludeMissing fun _lastRefreshedAt(): JsonField = lastRefreshedAt + /** + * Returns the raw JSON value of [lastRotationAt]. + * + * Unlike [lastRotationAt], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("last_rotation_at") + @ExcludeMissing + fun _lastRotationAt(): JsonField = lastRotationAt + + /** + * Returns the raw JSON value of [litellmBudgetTable]. + * + * Unlike [litellmBudgetTable], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("litellm_budget_table") + @ExcludeMissing + fun _litellmBudgetTable(): JsonField = litellmBudgetTable + /** * Returns the raw JSON value of [maxBudget]. * @@ -1204,20 +1654,160 @@ private constructor( fun _maxParallelRequests(): JsonField = maxParallelRequests /** - * Returns the raw JSON value of [models]. + * Returns the raw JSON value of [metadata]. * - * Unlike [models], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. */ - @JsonProperty("models") + @JsonProperty("metadata") @ExcludeMissing - fun _models(): JsonField> = models + fun _metadata(): JsonField = metadata /** - * Returns the raw JSON value of [orgId]. + * Returns the raw JSON value of [modelMaxBudget]. * - * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [modelMaxBudget], this method doesn't throw if the JSON field has an + * unexpected type. */ - @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + @JsonProperty("model_max_budget") + @ExcludeMissing + fun _modelMaxBudget(): JsonField = modelMaxBudget + + /** + * Returns the raw JSON value of [modelSpend]. + * + * Unlike [modelSpend], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("model_spend") + @ExcludeMissing + fun _modelSpend(): JsonField = modelSpend + + /** + * Returns the raw JSON value of [models]. + * + * Unlike [models], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("models") + @ExcludeMissing + fun _models(): JsonField> = models + + /** + * Returns the raw JSON value of [objectPermission]. + * + * Unlike [objectPermission], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("object_permission") + @ExcludeMissing + fun _objectPermission(): JsonField = objectPermission + + /** + * Returns the raw JSON value of [objectPermissionId]. + * + * Unlike [objectPermissionId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("object_permission_id") + @ExcludeMissing + fun _objectPermissionId(): JsonField = objectPermissionId + + /** + * Returns the raw JSON value of [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [organizationMaxBudget]. + * + * Unlike [organizationMaxBudget], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("organization_max_budget") + @ExcludeMissing + fun _organizationMaxBudget(): JsonField = organizationMaxBudget + + /** + * Returns the raw JSON value of [organizationMetadata]. + * + * Unlike [organizationMetadata], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("organization_metadata") + @ExcludeMissing + fun _organizationMetadata(): JsonField = organizationMetadata + + /** + * Returns the raw JSON value of [organizationRpmLimit]. + * + * Unlike [organizationRpmLimit], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("organization_rpm_limit") + @ExcludeMissing + fun _organizationRpmLimit(): JsonField = organizationRpmLimit + + /** + * Returns the raw JSON value of [organizationTpmLimit]. + * + * Unlike [organizationTpmLimit], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("organization_tpm_limit") + @ExcludeMissing + fun _organizationTpmLimit(): JsonField = organizationTpmLimit + + /** + * Returns the raw JSON value of [permissions]. + * + * Unlike [permissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("permissions") + @ExcludeMissing + fun _permissions(): JsonField = permissions + + /** + * Returns the raw JSON value of [requestRoute]. + * + * Unlike [requestRoute], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("request_route") + @ExcludeMissing + fun _requestRoute(): JsonField = requestRoute + + /** + * Returns the raw JSON value of [rotationCount]. + * + * Unlike [rotationCount], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("rotation_count") + @ExcludeMissing + fun _rotationCount(): JsonField = rotationCount + + /** + * Returns the raw JSON value of [rotationInterval]. + * + * Unlike [rotationInterval], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("rotation_interval") + @ExcludeMissing + fun _rotationInterval(): JsonField = rotationInterval + + /** + * Returns the raw JSON value of [routerSettings]. + * + * Unlike [routerSettings], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("router_settings") + @ExcludeMissing + fun _routerSettings(): JsonField = routerSettings /** * Returns the raw JSON value of [rpmLimit]. @@ -1311,6 +1901,16 @@ private constructor( @ExcludeMissing fun _teamMember(): JsonField = teamMember + /** + * Returns the raw JSON value of [teamMemberRpmLimit]. + * + * Unlike [teamMemberRpmLimit], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("team_member_rpm_limit") + @ExcludeMissing + fun _teamMemberRpmLimit(): JsonField = teamMemberRpmLimit + /** * Returns the raw JSON value of [teamMemberSpend]. * @@ -1321,6 +1921,36 @@ private constructor( @ExcludeMissing fun _teamMemberSpend(): JsonField = teamMemberSpend + /** + * Returns the raw JSON value of [teamMemberTpmLimit]. + * + * Unlike [teamMemberTpmLimit], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("team_member_tpm_limit") + @ExcludeMissing + fun _teamMemberTpmLimit(): JsonField = teamMemberTpmLimit + + /** + * Returns the raw JSON value of [teamMetadata]. + * + * Unlike [teamMetadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("team_metadata") + @ExcludeMissing + fun _teamMetadata(): JsonField = teamMetadata + + /** + * Returns the raw JSON value of [teamModelAliases]. + * + * Unlike [teamModelAliases], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("team_model_aliases") + @ExcludeMissing + fun _teamModelAliases(): JsonField = teamModelAliases + /** * Returns the raw JSON value of [teamModels]. * @@ -1331,6 +1961,16 @@ private constructor( @ExcludeMissing fun _teamModels(): JsonField> = teamModels + /** + * Returns the raw JSON value of [teamObjectPermissionId]. + * + * Unlike [teamObjectPermissionId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("team_object_permission_id") + @ExcludeMissing + fun _teamObjectPermissionId(): JsonField = teamObjectPermissionId + /** * Returns the raw JSON value of [teamRpmLimit]. * @@ -1416,6 +2056,16 @@ private constructor( */ @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + /** + * Returns the raw JSON value of [userMaxBudget]. + * + * Unlike [userMaxBudget], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("user_max_budget") + @ExcludeMissing + fun _userMaxBudget(): JsonField = userMaxBudget + /** * Returns the raw JSON value of [userRole]. * @@ -1424,7 +2074,7 @@ private constructor( */ @JsonProperty("user_role") @ExcludeMissing - fun _userRole(): JsonField = userRole + fun _userRole(): JsonField = userRole /** * Returns the raw JSON value of [userRpmLimit]. @@ -1436,6 +2086,16 @@ private constructor( @ExcludeMissing fun _userRpmLimit(): JsonField = userRpmLimit + /** + * Returns the raw JSON value of [userSpend]. + * + * Unlike [userSpend], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("user_spend") + @ExcludeMissing + fun _userSpend(): JsonField = userSpend + /** * Returns the raw JSON value of [userTpmLimit]. * @@ -1468,14 +2128,16 @@ private constructor( class Builder internal constructor() { private var token: JsonField = JsonMissing.of() - private var aliases: JsonValue = JsonMissing.of() + private var aliases: JsonField = JsonMissing.of() private var allowedCacheControls: JsonField>? = null private var allowedModelRegion: JsonField = JsonMissing.of() + private var allowedRoutes: JsonField>? = null private var apiKey: JsonField = JsonMissing.of() + private var autoRotate: JsonField = JsonMissing.of() private var blocked: JsonField = JsonMissing.of() private var budgetDuration: JsonField = JsonMissing.of() private var budgetResetAt: JsonField = JsonMissing.of() - private var config: JsonValue = JsonMissing.of() + private var config: JsonField = JsonMissing.of() private var createdAt: JsonField = JsonMissing.of() private var createdBy: JsonField = JsonMissing.of() private var endUserId: JsonField = JsonMissing.of() @@ -1485,17 +2147,29 @@ private constructor( private var expires: JsonField = JsonMissing.of() private var keyAlias: JsonField = JsonMissing.of() private var keyName: JsonField = JsonMissing.of() + private var keyRotationAt: JsonField = JsonMissing.of() private var lastRefreshedAt: JsonField = JsonMissing.of() - private var llmBudgetTable: JsonValue = JsonMissing.of() + private var lastRotationAt: JsonField = JsonMissing.of() + private var litellmBudgetTable: JsonField = JsonMissing.of() private var maxBudget: JsonField = JsonMissing.of() private var maxParallelRequests: JsonField = JsonMissing.of() - private var metadata: JsonValue = JsonMissing.of() - private var modelMaxBudget: JsonValue = JsonMissing.of() - private var modelSpend: JsonValue = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var modelMaxBudget: JsonField = JsonMissing.of() + private var modelSpend: JsonField = JsonMissing.of() private var models: JsonField>? = null + private var objectPermission: JsonField = JsonMissing.of() + private var objectPermissionId: JsonField = JsonMissing.of() private var orgId: JsonField = JsonMissing.of() + private var organizationMaxBudget: JsonField = JsonMissing.of() + private var organizationMetadata: JsonField = JsonMissing.of() + private var organizationRpmLimit: JsonField = JsonMissing.of() + private var organizationTpmLimit: JsonField = JsonMissing.of() private var parentOtelSpan: JsonValue = JsonMissing.of() - private var permissions: JsonValue = JsonMissing.of() + private var permissions: JsonField = JsonMissing.of() + private var requestRoute: JsonField = JsonMissing.of() + private var rotationCount: JsonField = JsonMissing.of() + private var rotationInterval: JsonField = JsonMissing.of() + private var routerSettings: JsonField = JsonMissing.of() private var rpmLimit: JsonField = JsonMissing.of() private var rpmLimitPerModel: JsonField = JsonMissing.of() private var softBudget: JsonField = JsonMissing.of() @@ -1506,10 +2180,13 @@ private constructor( private var teamId: JsonField = JsonMissing.of() private var teamMaxBudget: JsonField = JsonMissing.of() private var teamMember: JsonField = JsonMissing.of() + private var teamMemberRpmLimit: JsonField = JsonMissing.of() private var teamMemberSpend: JsonField = JsonMissing.of() - private var teamMetadata: JsonValue = JsonMissing.of() - private var teamModelAliases: JsonValue = JsonMissing.of() + private var teamMemberTpmLimit: JsonField = JsonMissing.of() + private var teamMetadata: JsonField = JsonMissing.of() + private var teamModelAliases: JsonField = JsonMissing.of() private var teamModels: JsonField>? = null + private var teamObjectPermissionId: JsonField = JsonMissing.of() private var teamRpmLimit: JsonField = JsonMissing.of() private var teamSpend: JsonField = JsonMissing.of() private var teamTpmLimit: JsonField = JsonMissing.of() @@ -1517,10 +2194,13 @@ private constructor( private var tpmLimitPerModel: JsonField = JsonMissing.of() private var updatedAt: JsonField = JsonMissing.of() private var updatedBy: JsonField = JsonMissing.of() + private var user: JsonValue = JsonMissing.of() private var userEmail: JsonField = JsonMissing.of() private var userId: JsonField = JsonMissing.of() - private var userRole: JsonField = JsonMissing.of() + private var userMaxBudget: JsonField = JsonMissing.of() + private var userRole: JsonField = JsonMissing.of() private var userRpmLimit: JsonField = JsonMissing.of() + private var userSpend: JsonField = JsonMissing.of() private var userTpmLimit: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @@ -1531,7 +2211,9 @@ private constructor( allowedCacheControls = userApiKeyAuth.allowedCacheControls.map { it.toMutableList() } allowedModelRegion = userApiKeyAuth.allowedModelRegion + allowedRoutes = userApiKeyAuth.allowedRoutes.map { it.toMutableList() } apiKey = userApiKeyAuth.apiKey + autoRotate = userApiKeyAuth.autoRotate blocked = userApiKeyAuth.blocked budgetDuration = userApiKeyAuth.budgetDuration budgetResetAt = userApiKeyAuth.budgetResetAt @@ -1545,17 +2227,29 @@ private constructor( expires = userApiKeyAuth.expires keyAlias = userApiKeyAuth.keyAlias keyName = userApiKeyAuth.keyName + keyRotationAt = userApiKeyAuth.keyRotationAt lastRefreshedAt = userApiKeyAuth.lastRefreshedAt - llmBudgetTable = userApiKeyAuth.llmBudgetTable + lastRotationAt = userApiKeyAuth.lastRotationAt + litellmBudgetTable = userApiKeyAuth.litellmBudgetTable maxBudget = userApiKeyAuth.maxBudget maxParallelRequests = userApiKeyAuth.maxParallelRequests metadata = userApiKeyAuth.metadata modelMaxBudget = userApiKeyAuth.modelMaxBudget modelSpend = userApiKeyAuth.modelSpend models = userApiKeyAuth.models.map { it.toMutableList() } + objectPermission = userApiKeyAuth.objectPermission + objectPermissionId = userApiKeyAuth.objectPermissionId orgId = userApiKeyAuth.orgId + organizationMaxBudget = userApiKeyAuth.organizationMaxBudget + organizationMetadata = userApiKeyAuth.organizationMetadata + organizationRpmLimit = userApiKeyAuth.organizationRpmLimit + organizationTpmLimit = userApiKeyAuth.organizationTpmLimit parentOtelSpan = userApiKeyAuth.parentOtelSpan permissions = userApiKeyAuth.permissions + requestRoute = userApiKeyAuth.requestRoute + rotationCount = userApiKeyAuth.rotationCount + rotationInterval = userApiKeyAuth.rotationInterval + routerSettings = userApiKeyAuth.routerSettings rpmLimit = userApiKeyAuth.rpmLimit rpmLimitPerModel = userApiKeyAuth.rpmLimitPerModel softBudget = userApiKeyAuth.softBudget @@ -1566,10 +2260,13 @@ private constructor( teamId = userApiKeyAuth.teamId teamMaxBudget = userApiKeyAuth.teamMaxBudget teamMember = userApiKeyAuth.teamMember + teamMemberRpmLimit = userApiKeyAuth.teamMemberRpmLimit teamMemberSpend = userApiKeyAuth.teamMemberSpend + teamMemberTpmLimit = userApiKeyAuth.teamMemberTpmLimit teamMetadata = userApiKeyAuth.teamMetadata teamModelAliases = userApiKeyAuth.teamModelAliases teamModels = userApiKeyAuth.teamModels.map { it.toMutableList() } + teamObjectPermissionId = userApiKeyAuth.teamObjectPermissionId teamRpmLimit = userApiKeyAuth.teamRpmLimit teamSpend = userApiKeyAuth.teamSpend teamTpmLimit = userApiKeyAuth.teamTpmLimit @@ -1577,10 +2274,13 @@ private constructor( tpmLimitPerModel = userApiKeyAuth.tpmLimitPerModel updatedAt = userApiKeyAuth.updatedAt updatedBy = userApiKeyAuth.updatedBy + user = userApiKeyAuth.user userEmail = userApiKeyAuth.userEmail userId = userApiKeyAuth.userId + userMaxBudget = userApiKeyAuth.userMaxBudget userRole = userApiKeyAuth.userRole userRpmLimit = userApiKeyAuth.userRpmLimit + userSpend = userApiKeyAuth.userSpend userTpmLimit = userApiKeyAuth.userTpmLimit additionalProperties = userApiKeyAuth.additionalProperties.toMutableMap() } @@ -1599,7 +2299,16 @@ private constructor( */ fun token(token: JsonField) = apply { this.token = token } - fun aliases(aliases: JsonValue) = apply { this.aliases = aliases } + fun aliases(aliases: Aliases) = aliases(JsonField.of(aliases)) + + /** + * Sets [Builder.aliases] to an arbitrary JSON value. + * + * You should usually call [Builder.aliases] with a well-typed [Aliases] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun aliases(aliases: JsonField) = apply { this.aliases = aliases } fun allowedCacheControls(allowedCacheControls: List?) = allowedCacheControls(JsonField.ofNullable(allowedCacheControls)) @@ -1655,6 +2364,36 @@ private constructor( this.allowedModelRegion = allowedModelRegion } + fun allowedRoutes(allowedRoutes: List?) = + allowedRoutes(JsonField.ofNullable(allowedRoutes)) + + /** Alias for calling [Builder.allowedRoutes] with `allowedRoutes.orElse(null)`. */ + fun allowedRoutes(allowedRoutes: Optional>) = + allowedRoutes(allowedRoutes.getOrNull()) + + /** + * Sets [Builder.allowedRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedRoutes] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun allowedRoutes(allowedRoutes: JsonField>) = apply { + this.allowedRoutes = allowedRoutes.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [allowedRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedRoute(allowedRoute: JsonValue) = apply { + allowedRoutes = + (allowedRoutes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedRoutes", it).add(allowedRoute) + } + } + fun apiKey(apiKey: String?) = apiKey(JsonField.ofNullable(apiKey)) /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ @@ -1669,6 +2408,29 @@ private constructor( */ fun apiKey(apiKey: JsonField) = apply { this.apiKey = apiKey } + fun autoRotate(autoRotate: Boolean?) = autoRotate(JsonField.ofNullable(autoRotate)) + + /** + * Alias for [Builder.autoRotate]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun autoRotate(autoRotate: Boolean) = autoRotate(autoRotate as Boolean?) + + /** Alias for calling [Builder.autoRotate] with `autoRotate.orElse(null)`. */ + fun autoRotate(autoRotate: Optional) = autoRotate(autoRotate.getOrNull()) + + /** + * Sets [Builder.autoRotate] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRotate] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun autoRotate(autoRotate: JsonField) = apply { + this.autoRotate = autoRotate + } + fun blocked(blocked: Boolean?) = blocked(JsonField.ofNullable(blocked)) /** @@ -1728,7 +2490,16 @@ private constructor( this.budgetResetAt = budgetResetAt } - fun config(config: JsonValue) = apply { this.config = config } + fun config(config: Config) = config(JsonField.of(config)) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [Config] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun config(config: JsonField) = apply { this.config = config } fun createdAt(createdAt: OffsetDateTime?) = createdAt(JsonField.ofNullable(createdAt)) @@ -1910,6 +2681,24 @@ private constructor( */ fun keyName(keyName: JsonField) = apply { this.keyName = keyName } + fun keyRotationAt(keyRotationAt: OffsetDateTime?) = + keyRotationAt(JsonField.ofNullable(keyRotationAt)) + + /** Alias for calling [Builder.keyRotationAt] with `keyRotationAt.orElse(null)`. */ + fun keyRotationAt(keyRotationAt: Optional) = + keyRotationAt(keyRotationAt.getOrNull()) + + /** + * Sets [Builder.keyRotationAt] to an arbitrary JSON value. + * + * You should usually call [Builder.keyRotationAt] with a well-typed + * [OffsetDateTime] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun keyRotationAt(keyRotationAt: JsonField) = apply { + this.keyRotationAt = keyRotationAt + } + fun lastRefreshedAt(lastRefreshedAt: Double?) = lastRefreshedAt(JsonField.ofNullable(lastRefreshedAt)) @@ -1938,8 +2727,45 @@ private constructor( this.lastRefreshedAt = lastRefreshedAt } - fun llmBudgetTable(llmBudgetTable: JsonValue) = apply { - this.llmBudgetTable = llmBudgetTable + fun lastRotationAt(lastRotationAt: OffsetDateTime?) = + lastRotationAt(JsonField.ofNullable(lastRotationAt)) + + /** + * Alias for calling [Builder.lastRotationAt] with `lastRotationAt.orElse(null)`. + */ + fun lastRotationAt(lastRotationAt: Optional) = + lastRotationAt(lastRotationAt.getOrNull()) + + /** + * Sets [Builder.lastRotationAt] to an arbitrary JSON value. + * + * You should usually call [Builder.lastRotationAt] with a well-typed + * [OffsetDateTime] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun lastRotationAt(lastRotationAt: JsonField) = apply { + this.lastRotationAt = lastRotationAt + } + + fun litellmBudgetTable(litellmBudgetTable: LitellmBudgetTable?) = + litellmBudgetTable(JsonField.ofNullable(litellmBudgetTable)) + + /** + * Alias for calling [Builder.litellmBudgetTable] with + * `litellmBudgetTable.orElse(null)`. + */ + fun litellmBudgetTable(litellmBudgetTable: Optional) = + litellmBudgetTable(litellmBudgetTable.getOrNull()) + + /** + * Sets [Builder.litellmBudgetTable] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmBudgetTable] with a well-typed + * [LitellmBudgetTable] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun litellmBudgetTable(litellmBudgetTable: JsonField) = apply { + this.litellmBudgetTable = litellmBudgetTable } fun maxBudget(maxBudget: Double?) = maxBudget(JsonField.ofNullable(maxBudget)) @@ -1992,13 +2818,43 @@ private constructor( this.maxParallelRequests = maxParallelRequests } - fun metadata(metadata: JsonValue) = apply { this.metadata = metadata } + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun modelMaxBudget(modelMaxBudget: ModelMaxBudget) = + modelMaxBudget(JsonField.of(modelMaxBudget)) - fun modelMaxBudget(modelMaxBudget: JsonValue) = apply { + /** + * Sets [Builder.modelMaxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.modelMaxBudget] with a well-typed + * [ModelMaxBudget] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun modelMaxBudget(modelMaxBudget: JsonField) = apply { this.modelMaxBudget = modelMaxBudget } - fun modelSpend(modelSpend: JsonValue) = apply { this.modelSpend = modelSpend } + fun modelSpend(modelSpend: ModelSpend) = modelSpend(JsonField.of(modelSpend)) + + /** + * Sets [Builder.modelSpend] to an arbitrary JSON value. + * + * You should usually call [Builder.modelSpend] with a well-typed [ModelSpend] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun modelSpend(modelSpend: JsonField) = apply { + this.modelSpend = modelSpend + } fun models(models: List) = models(JsonField.of(models)) @@ -2025,6 +2881,49 @@ private constructor( } } + /** Represents a LiteLLM_ObjectPermissionTable record */ + fun objectPermission(objectPermission: ObjectPermission?) = + objectPermission(JsonField.ofNullable(objectPermission)) + + /** + * Alias for calling [Builder.objectPermission] with + * `objectPermission.orElse(null)`. + */ + fun objectPermission(objectPermission: Optional) = + objectPermission(objectPermission.getOrNull()) + + /** + * Sets [Builder.objectPermission] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermission] with a well-typed + * [ObjectPermission] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun objectPermission(objectPermission: JsonField) = apply { + this.objectPermission = objectPermission + } + + fun objectPermissionId(objectPermissionId: String?) = + objectPermissionId(JsonField.ofNullable(objectPermissionId)) + + /** + * Alias for calling [Builder.objectPermissionId] with + * `objectPermissionId.orElse(null)`. + */ + fun objectPermissionId(objectPermissionId: Optional) = + objectPermissionId(objectPermissionId.getOrNull()) + + /** + * Sets [Builder.objectPermissionId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermissionId] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun objectPermissionId(objectPermissionId: JsonField) = apply { + this.objectPermissionId = objectPermissionId + } + fun orgId(orgId: String?) = orgId(JsonField.ofNullable(orgId)) /** Alias for calling [Builder.orgId] with `orgId.orElse(null)`. */ @@ -2039,26 +2938,230 @@ private constructor( */ fun orgId(orgId: JsonField) = apply { this.orgId = orgId } - fun parentOtelSpan(parentOtelSpan: JsonValue) = apply { - this.parentOtelSpan = parentOtelSpan - } - - fun permissions(permissions: JsonValue) = apply { this.permissions = permissions } - - fun rpmLimit(rpmLimit: Long?) = rpmLimit(JsonField.ofNullable(rpmLimit)) + fun organizationMaxBudget(organizationMaxBudget: Double?) = + organizationMaxBudget(JsonField.ofNullable(organizationMaxBudget)) /** - * Alias for [Builder.rpmLimit]. + * Alias for [Builder.organizationMaxBudget]. * * This unboxed primitive overload exists for backwards compatibility. */ - fun rpmLimit(rpmLimit: Long) = rpmLimit(rpmLimit as Long?) + fun organizationMaxBudget(organizationMaxBudget: Double) = + organizationMaxBudget(organizationMaxBudget as Double?) - /** Alias for calling [Builder.rpmLimit] with `rpmLimit.orElse(null)`. */ - fun rpmLimit(rpmLimit: Optional) = rpmLimit(rpmLimit.getOrNull()) + /** + * Alias for calling [Builder.organizationMaxBudget] with + * `organizationMaxBudget.orElse(null)`. + */ + fun organizationMaxBudget(organizationMaxBudget: Optional) = + organizationMaxBudget(organizationMaxBudget.getOrNull()) /** - * Sets [Builder.rpmLimit] to an arbitrary JSON value. + * Sets [Builder.organizationMaxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.organizationMaxBudget] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun organizationMaxBudget(organizationMaxBudget: JsonField) = apply { + this.organizationMaxBudget = organizationMaxBudget + } + + fun organizationMetadata(organizationMetadata: OrganizationMetadata?) = + organizationMetadata(JsonField.ofNullable(organizationMetadata)) + + /** + * Alias for calling [Builder.organizationMetadata] with + * `organizationMetadata.orElse(null)`. + */ + fun organizationMetadata(organizationMetadata: Optional) = + organizationMetadata(organizationMetadata.getOrNull()) + + /** + * Sets [Builder.organizationMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.organizationMetadata] with a well-typed + * [OrganizationMetadata] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun organizationMetadata(organizationMetadata: JsonField) = + apply { + this.organizationMetadata = organizationMetadata + } + + fun organizationRpmLimit(organizationRpmLimit: Long?) = + organizationRpmLimit(JsonField.ofNullable(organizationRpmLimit)) + + /** + * Alias for [Builder.organizationRpmLimit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun organizationRpmLimit(organizationRpmLimit: Long) = + organizationRpmLimit(organizationRpmLimit as Long?) + + /** + * Alias for calling [Builder.organizationRpmLimit] with + * `organizationRpmLimit.orElse(null)`. + */ + fun organizationRpmLimit(organizationRpmLimit: Optional) = + organizationRpmLimit(organizationRpmLimit.getOrNull()) + + /** + * Sets [Builder.organizationRpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.organizationRpmLimit] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun organizationRpmLimit(organizationRpmLimit: JsonField) = apply { + this.organizationRpmLimit = organizationRpmLimit + } + + fun organizationTpmLimit(organizationTpmLimit: Long?) = + organizationTpmLimit(JsonField.ofNullable(organizationTpmLimit)) + + /** + * Alias for [Builder.organizationTpmLimit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun organizationTpmLimit(organizationTpmLimit: Long) = + organizationTpmLimit(organizationTpmLimit as Long?) + + /** + * Alias for calling [Builder.organizationTpmLimit] with + * `organizationTpmLimit.orElse(null)`. + */ + fun organizationTpmLimit(organizationTpmLimit: Optional) = + organizationTpmLimit(organizationTpmLimit.getOrNull()) + + /** + * Sets [Builder.organizationTpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.organizationTpmLimit] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun organizationTpmLimit(organizationTpmLimit: JsonField) = apply { + this.organizationTpmLimit = organizationTpmLimit + } + + fun parentOtelSpan(parentOtelSpan: JsonValue) = apply { + this.parentOtelSpan = parentOtelSpan + } + + fun permissions(permissions: Permissions) = permissions(JsonField.of(permissions)) + + /** + * Sets [Builder.permissions] to an arbitrary JSON value. + * + * You should usually call [Builder.permissions] with a well-typed [Permissions] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun permissions(permissions: JsonField) = apply { + this.permissions = permissions + } + + fun requestRoute(requestRoute: String?) = + requestRoute(JsonField.ofNullable(requestRoute)) + + /** Alias for calling [Builder.requestRoute] with `requestRoute.orElse(null)`. */ + fun requestRoute(requestRoute: Optional) = + requestRoute(requestRoute.getOrNull()) + + /** + * Sets [Builder.requestRoute] to an arbitrary JSON value. + * + * You should usually call [Builder.requestRoute] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun requestRoute(requestRoute: JsonField) = apply { + this.requestRoute = requestRoute + } + + fun rotationCount(rotationCount: Long?) = + rotationCount(JsonField.ofNullable(rotationCount)) + + /** + * Alias for [Builder.rotationCount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun rotationCount(rotationCount: Long) = rotationCount(rotationCount as Long?) + + /** Alias for calling [Builder.rotationCount] with `rotationCount.orElse(null)`. */ + fun rotationCount(rotationCount: Optional) = + rotationCount(rotationCount.getOrNull()) + + /** + * Sets [Builder.rotationCount] to an arbitrary JSON value. + * + * You should usually call [Builder.rotationCount] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun rotationCount(rotationCount: JsonField) = apply { + this.rotationCount = rotationCount + } + + fun rotationInterval(rotationInterval: String?) = + rotationInterval(JsonField.ofNullable(rotationInterval)) + + /** + * Alias for calling [Builder.rotationInterval] with + * `rotationInterval.orElse(null)`. + */ + fun rotationInterval(rotationInterval: Optional) = + rotationInterval(rotationInterval.getOrNull()) + + /** + * Sets [Builder.rotationInterval] to an arbitrary JSON value. + * + * You should usually call [Builder.rotationInterval] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun rotationInterval(rotationInterval: JsonField) = apply { + this.rotationInterval = rotationInterval + } + + fun routerSettings(routerSettings: RouterSettings?) = + routerSettings(JsonField.ofNullable(routerSettings)) + + /** + * Alias for calling [Builder.routerSettings] with `routerSettings.orElse(null)`. + */ + fun routerSettings(routerSettings: Optional) = + routerSettings(routerSettings.getOrNull()) + + /** + * Sets [Builder.routerSettings] to an arbitrary JSON value. + * + * You should usually call [Builder.routerSettings] with a well-typed + * [RouterSettings] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun routerSettings(routerSettings: JsonField) = apply { + this.routerSettings = routerSettings + } + + fun rpmLimit(rpmLimit: Long?) = rpmLimit(JsonField.ofNullable(rpmLimit)) + + /** + * Alias for [Builder.rpmLimit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun rpmLimit(rpmLimit: Long) = rpmLimit(rpmLimit as Long?) + + /** Alias for calling [Builder.rpmLimit] with `rpmLimit.orElse(null)`. */ + fun rpmLimit(rpmLimit: Optional) = rpmLimit(rpmLimit.getOrNull()) + + /** + * Sets [Builder.rpmLimit] to an arbitrary JSON value. * * You should usually call [Builder.rpmLimit] with a well-typed [Long] value * instead. This method is primarily for setting the field to an undocumented or not @@ -2217,6 +3320,35 @@ private constructor( this.teamMember = teamMember } + fun teamMemberRpmLimit(teamMemberRpmLimit: Long?) = + teamMemberRpmLimit(JsonField.ofNullable(teamMemberRpmLimit)) + + /** + * Alias for [Builder.teamMemberRpmLimit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun teamMemberRpmLimit(teamMemberRpmLimit: Long) = + teamMemberRpmLimit(teamMemberRpmLimit as Long?) + + /** + * Alias for calling [Builder.teamMemberRpmLimit] with + * `teamMemberRpmLimit.orElse(null)`. + */ + fun teamMemberRpmLimit(teamMemberRpmLimit: Optional) = + teamMemberRpmLimit(teamMemberRpmLimit.getOrNull()) + + /** + * Sets [Builder.teamMemberRpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.teamMemberRpmLimit] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun teamMemberRpmLimit(teamMemberRpmLimit: JsonField) = apply { + this.teamMemberRpmLimit = teamMemberRpmLimit + } + fun teamMemberSpend(teamMemberSpend: Double?) = teamMemberSpend(JsonField.ofNullable(teamMemberSpend)) @@ -2245,11 +3377,71 @@ private constructor( this.teamMemberSpend = teamMemberSpend } - fun teamMetadata(teamMetadata: JsonValue) = apply { + fun teamMemberTpmLimit(teamMemberTpmLimit: Long?) = + teamMemberTpmLimit(JsonField.ofNullable(teamMemberTpmLimit)) + + /** + * Alias for [Builder.teamMemberTpmLimit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun teamMemberTpmLimit(teamMemberTpmLimit: Long) = + teamMemberTpmLimit(teamMemberTpmLimit as Long?) + + /** + * Alias for calling [Builder.teamMemberTpmLimit] with + * `teamMemberTpmLimit.orElse(null)`. + */ + fun teamMemberTpmLimit(teamMemberTpmLimit: Optional) = + teamMemberTpmLimit(teamMemberTpmLimit.getOrNull()) + + /** + * Sets [Builder.teamMemberTpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.teamMemberTpmLimit] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun teamMemberTpmLimit(teamMemberTpmLimit: JsonField) = apply { + this.teamMemberTpmLimit = teamMemberTpmLimit + } + + fun teamMetadata(teamMetadata: TeamMetadata?) = + teamMetadata(JsonField.ofNullable(teamMetadata)) + + /** Alias for calling [Builder.teamMetadata] with `teamMetadata.orElse(null)`. */ + fun teamMetadata(teamMetadata: Optional) = + teamMetadata(teamMetadata.getOrNull()) + + /** + * Sets [Builder.teamMetadata] to an arbitrary JSON value. + * + * You should usually call [Builder.teamMetadata] with a well-typed [TeamMetadata] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun teamMetadata(teamMetadata: JsonField) = apply { this.teamMetadata = teamMetadata } - fun teamModelAliases(teamModelAliases: JsonValue) = apply { + fun teamModelAliases(teamModelAliases: TeamModelAliases?) = + teamModelAliases(JsonField.ofNullable(teamModelAliases)) + + /** + * Alias for calling [Builder.teamModelAliases] with + * `teamModelAliases.orElse(null)`. + */ + fun teamModelAliases(teamModelAliases: Optional) = + teamModelAliases(teamModelAliases.getOrNull()) + + /** + * Sets [Builder.teamModelAliases] to an arbitrary JSON value. + * + * You should usually call [Builder.teamModelAliases] with a well-typed + * [TeamModelAliases] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun teamModelAliases(teamModelAliases: JsonField) = apply { this.teamModelAliases = teamModelAliases } @@ -2278,6 +3470,27 @@ private constructor( } } + fun teamObjectPermissionId(teamObjectPermissionId: String?) = + teamObjectPermissionId(JsonField.ofNullable(teamObjectPermissionId)) + + /** + * Alias for calling [Builder.teamObjectPermissionId] with + * `teamObjectPermissionId.orElse(null)`. + */ + fun teamObjectPermissionId(teamObjectPermissionId: Optional) = + teamObjectPermissionId(teamObjectPermissionId.getOrNull()) + + /** + * Sets [Builder.teamObjectPermissionId] to an arbitrary JSON value. + * + * You should usually call [Builder.teamObjectPermissionId] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun teamObjectPermissionId(teamObjectPermissionId: JsonField) = apply { + this.teamObjectPermissionId = teamObjectPermissionId + } + fun teamRpmLimit(teamRpmLimit: Long?) = teamRpmLimit(JsonField.ofNullable(teamRpmLimit)) @@ -2423,6 +3636,8 @@ private constructor( */ fun updatedBy(updatedBy: JsonField) = apply { this.updatedBy = updatedBy } + fun user(user: JsonValue) = apply { this.user = user } + fun userEmail(userEmail: String?) = userEmail(JsonField.ofNullable(userEmail)) /** Alias for calling [Builder.userEmail] with `userEmail.orElse(null)`. */ @@ -2451,6 +3666,31 @@ private constructor( */ fun userId(userId: JsonField) = apply { this.userId = userId } + fun userMaxBudget(userMaxBudget: Double?) = + userMaxBudget(JsonField.ofNullable(userMaxBudget)) + + /** + * Alias for [Builder.userMaxBudget]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun userMaxBudget(userMaxBudget: Double) = userMaxBudget(userMaxBudget as Double?) + + /** Alias for calling [Builder.userMaxBudget] with `userMaxBudget.orElse(null)`. */ + fun userMaxBudget(userMaxBudget: Optional) = + userMaxBudget(userMaxBudget.getOrNull()) + + /** + * Sets [Builder.userMaxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.userMaxBudget] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun userMaxBudget(userMaxBudget: JsonField) = apply { + this.userMaxBudget = userMaxBudget + } + /** * Admin Roles: PROXY_ADMIN: admin over the platform PROXY_ADMIN_VIEW_ONLY: can * login, view all own keys, view all spend ORG_ADMIN: admin over a specific @@ -2464,19 +3704,19 @@ private constructor( * * Customer Roles: CUSTOMER: External users -> these are customers */ - fun userRole(userRole: UserRole?) = userRole(JsonField.ofNullable(userRole)) + fun userRole(userRole: UserRoles?) = userRole(JsonField.ofNullable(userRole)) /** Alias for calling [Builder.userRole] with `userRole.orElse(null)`. */ - fun userRole(userRole: Optional) = userRole(userRole.getOrNull()) + fun userRole(userRole: Optional) = userRole(userRole.getOrNull()) /** * Sets [Builder.userRole] to an arbitrary JSON value. * - * You should usually call [Builder.userRole] with a well-typed [UserRole] value + * You should usually call [Builder.userRole] with a well-typed [UserRoles] value * instead. This method is primarily for setting the field to an undocumented or not * yet supported value. */ - fun userRole(userRole: JsonField) = apply { this.userRole = userRole } + fun userRole(userRole: JsonField) = apply { this.userRole = userRole } fun userRpmLimit(userRpmLimit: Long?) = userRpmLimit(JsonField.ofNullable(userRpmLimit)) @@ -2503,6 +3743,27 @@ private constructor( this.userRpmLimit = userRpmLimit } + fun userSpend(userSpend: Double?) = userSpend(JsonField.ofNullable(userSpend)) + + /** + * Alias for [Builder.userSpend]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun userSpend(userSpend: Double) = userSpend(userSpend as Double?) + + /** Alias for calling [Builder.userSpend] with `userSpend.orElse(null)`. */ + fun userSpend(userSpend: Optional) = userSpend(userSpend.getOrNull()) + + /** + * Sets [Builder.userSpend] to an arbitrary JSON value. + * + * You should usually call [Builder.userSpend] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun userSpend(userSpend: JsonField) = apply { this.userSpend = userSpend } + fun userTpmLimit(userTpmLimit: Long?) = userTpmLimit(JsonField.ofNullable(userTpmLimit)) @@ -2561,7 +3822,9 @@ private constructor( aliases, (allowedCacheControls ?: JsonMissing.of()).map { it.toImmutable() }, allowedModelRegion, + (allowedRoutes ?: JsonMissing.of()).map { it.toImmutable() }, apiKey, + autoRotate, blocked, budgetDuration, budgetResetAt, @@ -2575,17 +3838,29 @@ private constructor( expires, keyAlias, keyName, + keyRotationAt, lastRefreshedAt, - llmBudgetTable, + lastRotationAt, + litellmBudgetTable, maxBudget, maxParallelRequests, metadata, modelMaxBudget, modelSpend, (models ?: JsonMissing.of()).map { it.toImmutable() }, + objectPermission, + objectPermissionId, orgId, + organizationMaxBudget, + organizationMetadata, + organizationRpmLimit, + organizationTpmLimit, parentOtelSpan, permissions, + requestRoute, + rotationCount, + rotationInterval, + routerSettings, rpmLimit, rpmLimitPerModel, softBudget, @@ -2596,10 +3871,13 @@ private constructor( teamId, teamMaxBudget, teamMember, + teamMemberRpmLimit, teamMemberSpend, + teamMemberTpmLimit, teamMetadata, teamModelAliases, (teamModels ?: JsonMissing.of()).map { it.toImmutable() }, + teamObjectPermissionId, teamRpmLimit, teamSpend, teamTpmLimit, @@ -2607,10 +3885,13 @@ private constructor( tpmLimitPerModel, updatedAt, updatedBy, + user, userEmail, userId, + userMaxBudget, userRole, userRpmLimit, + userSpend, userTpmLimit, additionalProperties.toMutableMap(), ) @@ -2624,12 +3905,16 @@ private constructor( } token() + aliases().ifPresent { it.validate() } allowedCacheControls() - allowedModelRegion() + allowedModelRegion().ifPresent { it.validate() } + allowedRoutes() apiKey() + autoRotate() blocked() budgetDuration() budgetResetAt() + config().ifPresent { it.validate() } createdAt() createdBy() endUserId() @@ -2639,11 +3924,28 @@ private constructor( expires().ifPresent { it.validate() } keyAlias() keyName() + keyRotationAt() lastRefreshedAt() + lastRotationAt() + litellmBudgetTable().ifPresent { it.validate() } maxBudget() maxParallelRequests() + metadata().ifPresent { it.validate() } + modelMaxBudget().ifPresent { it.validate() } + modelSpend().ifPresent { it.validate() } models() + objectPermission().ifPresent { it.validate() } + objectPermissionId() orgId() + organizationMaxBudget() + organizationMetadata().ifPresent { it.validate() } + organizationRpmLimit() + organizationTpmLimit() + permissions().ifPresent { it.validate() } + requestRoute() + rotationCount() + rotationInterval() + routerSettings().ifPresent { it.validate() } rpmLimit() rpmLimitPerModel().ifPresent { it.validate() } softBudget() @@ -2654,8 +3956,13 @@ private constructor( teamId() teamMaxBudget() teamMember().ifPresent { it.validate() } + teamMemberRpmLimit() teamMemberSpend() + teamMemberTpmLimit() + teamMetadata().ifPresent { it.validate() } + teamModelAliases().ifPresent { it.validate() } teamModels() + teamObjectPermissionId() teamRpmLimit() teamSpend() teamTpmLimit() @@ -2665,56 +3972,252 @@ private constructor( updatedBy() userEmail() userId() - userRole() + userMaxBudget() + userRole().ifPresent { it.validate() } userRpmLimit() + userSpend() userTpmLimit() validated = true } - class AllowedModelRegion + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (token.asKnown().isPresent) 1 else 0) + + (aliases.asKnown().getOrNull()?.validity() ?: 0) + + (allowedCacheControls.asKnown().getOrNull()?.size ?: 0) + + (allowedModelRegion.asKnown().getOrNull()?.validity() ?: 0) + + (allowedRoutes.asKnown().getOrNull()?.size ?: 0) + + (if (apiKey.asKnown().isPresent) 1 else 0) + + (if (autoRotate.asKnown().isPresent) 1 else 0) + + (if (blocked.asKnown().isPresent) 1 else 0) + + (if (budgetDuration.asKnown().isPresent) 1 else 0) + + (if (budgetResetAt.asKnown().isPresent) 1 else 0) + + (config.asKnown().getOrNull()?.validity() ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (createdBy.asKnown().isPresent) 1 else 0) + + (if (endUserId.asKnown().isPresent) 1 else 0) + + (if (endUserMaxBudget.asKnown().isPresent) 1 else 0) + + (if (endUserRpmLimit.asKnown().isPresent) 1 else 0) + + (if (endUserTpmLimit.asKnown().isPresent) 1 else 0) + + (expires.asKnown().getOrNull()?.validity() ?: 0) + + (if (keyAlias.asKnown().isPresent) 1 else 0) + + (if (keyName.asKnown().isPresent) 1 else 0) + + (if (keyRotationAt.asKnown().isPresent) 1 else 0) + + (if (lastRefreshedAt.asKnown().isPresent) 1 else 0) + + (if (lastRotationAt.asKnown().isPresent) 1 else 0) + + (litellmBudgetTable.asKnown().getOrNull()?.validity() ?: 0) + + (if (maxBudget.asKnown().isPresent) 1 else 0) + + (if (maxParallelRequests.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (modelMaxBudget.asKnown().getOrNull()?.validity() ?: 0) + + (modelSpend.asKnown().getOrNull()?.validity() ?: 0) + + (models.asKnown().getOrNull()?.size ?: 0) + + (objectPermission.asKnown().getOrNull()?.validity() ?: 0) + + (if (objectPermissionId.asKnown().isPresent) 1 else 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (if (organizationMaxBudget.asKnown().isPresent) 1 else 0) + + (organizationMetadata.asKnown().getOrNull()?.validity() ?: 0) + + (if (organizationRpmLimit.asKnown().isPresent) 1 else 0) + + (if (organizationTpmLimit.asKnown().isPresent) 1 else 0) + + (permissions.asKnown().getOrNull()?.validity() ?: 0) + + (if (requestRoute.asKnown().isPresent) 1 else 0) + + (if (rotationCount.asKnown().isPresent) 1 else 0) + + (if (rotationInterval.asKnown().isPresent) 1 else 0) + + (routerSettings.asKnown().getOrNull()?.validity() ?: 0) + + (if (rpmLimit.asKnown().isPresent) 1 else 0) + + (rpmLimitPerModel.asKnown().getOrNull()?.validity() ?: 0) + + (if (softBudget.asKnown().isPresent) 1 else 0) + + (if (softBudgetCooldown.asKnown().isPresent) 1 else 0) + + (if (spend.asKnown().isPresent) 1 else 0) + + (if (teamAlias.asKnown().isPresent) 1 else 0) + + (if (teamBlocked.asKnown().isPresent) 1 else 0) + + (if (teamId.asKnown().isPresent) 1 else 0) + + (if (teamMaxBudget.asKnown().isPresent) 1 else 0) + + (teamMember.asKnown().getOrNull()?.validity() ?: 0) + + (if (teamMemberRpmLimit.asKnown().isPresent) 1 else 0) + + (if (teamMemberSpend.asKnown().isPresent) 1 else 0) + + (if (teamMemberTpmLimit.asKnown().isPresent) 1 else 0) + + (teamMetadata.asKnown().getOrNull()?.validity() ?: 0) + + (teamModelAliases.asKnown().getOrNull()?.validity() ?: 0) + + (teamModels.asKnown().getOrNull()?.size ?: 0) + + (if (teamObjectPermissionId.asKnown().isPresent) 1 else 0) + + (if (teamRpmLimit.asKnown().isPresent) 1 else 0) + + (if (teamSpend.asKnown().isPresent) 1 else 0) + + (if (teamTpmLimit.asKnown().isPresent) 1 else 0) + + (if (tpmLimit.asKnown().isPresent) 1 else 0) + + (tpmLimitPerModel.asKnown().getOrNull()?.validity() ?: 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + (if (updatedBy.asKnown().isPresent) 1 else 0) + + (if (userEmail.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + (if (userMaxBudget.asKnown().isPresent) 1 else 0) + + (userRole.asKnown().getOrNull()?.validity() ?: 0) + + (if (userRpmLimit.asKnown().isPresent) 1 else 0) + + (if (userSpend.asKnown().isPresent) 1 else 0) + + (if (userTpmLimit.asKnown().isPresent) 1 else 0) + + class Aliases @JsonCreator - private constructor(private val value: JsonField) : Enum { + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { - /** - * Returns this class instance's raw value. - * - * This is usually only useful if this instance was deserialized from data that - * doesn't match any known member, and you want to know that value. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. - */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) companion object { - @JvmField val EU = of("eu") + /** Returns a mutable builder for constructing an instance of [Aliases]. */ + @JvmStatic fun builder() = Builder() + } - @JvmField val US = of("us") + /** A builder for [Aliases]. */ + class Builder internal constructor() { - @JvmStatic fun of(value: String) = AllowedModelRegion(JsonField.of(value)) - } + private var additionalProperties: MutableMap = mutableMapOf() - /** An enum containing [AllowedModelRegion]'s known values. */ - enum class Known { - EU, - US, - } + @JvmSynthetic + internal fun from(aliases: Aliases) = apply { + additionalProperties = aliases.additionalProperties.toMutableMap() + } - /** - * An enum containing [AllowedModelRegion]'s known values, as well as an [_UNKNOWN] - * member. - * - * An instance of [AllowedModelRegion] can contain an unknown value in a couple of - * cases: - * - It was deserialized from data that doesn't match any known member. For example, - * if the SDK is on an older version than the API, then the API may respond with - * new members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. - */ - enum class Value { - EU, - US, - /** + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Aliases]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Aliases = Aliases(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Aliases = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Aliases && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Aliases{additionalProperties=$additionalProperties}" + } + + class AllowedModelRegion + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EU = of("eu") + + @JvmField val US = of("us") + + @JvmStatic fun of(value: String) = AllowedModelRegion(JsonField.of(value)) + } + + /** An enum containing [AllowedModelRegion]'s known values. */ + enum class Known { + EU, + US, + } + + /** + * An enum containing [AllowedModelRegion]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [AllowedModelRegion] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + EU, + US, + /** * An enum member indicating that [AllowedModelRegion] was instantiated with an * unknown value. */ @@ -2766,12 +4269,39 @@ private constructor( HanzoInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AllowedModelRegion = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is AllowedModelRegion && value == other.value /* spotless:on */ + return other is AllowedModelRegion && value == other.value } override fun hashCode() = value.hashCode() @@ -2779,6 +4309,110 @@ private constructor( override fun toString() = value.toString() } + class Config + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Config]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Config]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(config: Config) = apply { + additionalProperties = config.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Config]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Config = Config(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Config = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Config && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Config{additionalProperties=$additionalProperties}" + } + @JsonDeserialize(using = Expires.Deserializer::class) @JsonSerialize(using = Expires.Serializer::class) class Expires @@ -2802,13 +4436,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { string != null -> visitor.visitString(string) offsetDateTime != null -> visitor.visitOffsetDateTime(offsetDateTime) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -2827,15 +4460,43 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitOffsetDateTime(offsetDateTime: OffsetDateTime) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Expires && string == other.string && offsetDateTime == other.offsetDateTime /* spotless:on */ + return other is Expires && + string == other.string && + offsetDateTime == other.offsetDateTime } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, offsetDateTime) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(string, offsetDateTime) override fun toString(): String = when { @@ -2884,14 +4545,29 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Expires { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef())?.let { - return Expires(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef())?.let { - return Expires(offsetDateTime = it, _json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Expires(offsetDateTime = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Expires(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Expires(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() } - - return Expires(_json = json) } } @@ -2913,7 +4589,7 @@ private constructor( } } - class RpmLimitPerModel + class LitellmBudgetTable @JsonCreator private constructor( @com.fasterxml.jackson.annotation.JsonValue @@ -2929,19 +4605,21 @@ private constructor( companion object { /** - * Returns a mutable builder for constructing an instance of [RpmLimitPerModel]. + * Returns a mutable builder for constructing an instance of + * [LitellmBudgetTable]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [RpmLimitPerModel]. */ + /** A builder for [LitellmBudgetTable]. */ class Builder internal constructor() { private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(rpmLimitPerModel: RpmLimitPerModel) = apply { - additionalProperties = rpmLimitPerModel.additionalProperties.toMutableMap() + internal fun from(litellmBudgetTable: LitellmBudgetTable) = apply { + additionalProperties = + litellmBudgetTable.additionalProperties.toMutableMap() } fun additionalProperties(additionalProperties: Map) = apply { @@ -2967,17 +4645,17 @@ private constructor( } /** - * Returns an immutable instance of [RpmLimitPerModel]. + * Returns an immutable instance of [LitellmBudgetTable]. * * Further updates to this [Builder] will not mutate the returned instance. */ - fun build(): RpmLimitPerModel = - RpmLimitPerModel(additionalProperties.toImmutable()) + fun build(): LitellmBudgetTable = + LitellmBudgetTable(additionalProperties.toImmutable()) } private var validated: Boolean = false - fun validate(): RpmLimitPerModel = apply { + fun validate(): LitellmBudgetTable = apply { if (validated) { return@apply } @@ -2985,25 +4663,44 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is RpmLimitPerModel && additionalProperties == other.additionalProperties /* spotless:on */ + return other is LitellmBudgetTable && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode override fun toString() = - "RpmLimitPerModel{additionalProperties=$additionalProperties}" + "LitellmBudgetTable{additionalProperties=$additionalProperties}" } - class TpmLimitPerModel + class Metadata @JsonCreator private constructor( @com.fasterxml.jackson.annotation.JsonValue @@ -3018,20 +4715,18 @@ private constructor( companion object { - /** - * Returns a mutable builder for constructing an instance of [TpmLimitPerModel]. - */ + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [TpmLimitPerModel]. */ + /** A builder for [Metadata]. */ class Builder internal constructor() { private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(tpmLimitPerModel: TpmLimitPerModel) = apply { - additionalProperties = tpmLimitPerModel.additionalProperties.toMutableMap() + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() } fun additionalProperties(additionalProperties: Map) = apply { @@ -3057,17 +4752,16 @@ private constructor( } /** - * Returns an immutable instance of [TpmLimitPerModel]. + * Returns an immutable instance of [Metadata]. * * Further updates to this [Builder] will not mutate the returned instance. */ - fun build(): TpmLimitPerModel = - TpmLimitPerModel(additionalProperties.toImmutable()) + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) } private var validated: Boolean = false - fun validate(): TpmLimitPerModel = apply { + fun validate(): Metadata = apply { if (validated) { return@apply } @@ -3075,156 +4769,5458 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is TpmLimitPerModel && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Metadata && additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode - override fun toString() = - "TpmLimitPerModel{additionalProperties=$additionalProperties}" + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" } - /** - * Admin Roles: PROXY_ADMIN: admin over the platform PROXY_ADMIN_VIEW_ONLY: can login, - * view all own keys, view all spend ORG_ADMIN: admin over a specific organization, can - * create teams, users only within their organization + class ModelMaxBudget + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ModelMaxBudget]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelMaxBudget]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelMaxBudget: ModelMaxBudget) = apply { + additionalProperties = modelMaxBudget.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelMaxBudget]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelMaxBudget = ModelMaxBudget(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelMaxBudget = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelMaxBudget && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ModelMaxBudget{additionalProperties=$additionalProperties}" + } + + class ModelSpend + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelSpend]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelSpend]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelSpend: ModelSpend) = apply { + additionalProperties = modelSpend.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelSpend]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelSpend = ModelSpend(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelSpend = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelSpend && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelSpend{additionalProperties=$additionalProperties}" + } + + /** Represents a LiteLLM_ObjectPermissionTable record */ + class ObjectPermission + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val objectPermissionId: JsonField, + private val agentAccessGroups: JsonField>, + private val agents: JsonField>, + private val mcpAccessGroups: JsonField>, + private val mcpServers: JsonField>, + private val mcpToolPermissions: JsonField, + private val vectorStores: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("object_permission_id") + @ExcludeMissing + objectPermissionId: JsonField = JsonMissing.of(), + @JsonProperty("agent_access_groups") + @ExcludeMissing + agentAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("agents") + @ExcludeMissing + agents: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_access_groups") + @ExcludeMissing + mcpAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_servers") + @ExcludeMissing + mcpServers: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + mcpToolPermissions: JsonField = JsonMissing.of(), + @JsonProperty("vector_stores") + @ExcludeMissing + vectorStores: JsonField> = JsonMissing.of(), + ) : this( + objectPermissionId, + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun objectPermissionId(): String = + objectPermissionId.getRequired("object_permission_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun agentAccessGroups(): Optional> = + agentAccessGroups.getOptional("agent_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun agents(): Optional> = agents.getOptional("agents") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun mcpAccessGroups(): Optional> = + mcpAccessGroups.getOptional("mcp_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun mcpServers(): Optional> = mcpServers.getOptional("mcp_servers") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun mcpToolPermissions(): Optional = + mcpToolPermissions.getOptional("mcp_tool_permissions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun vectorStores(): Optional> = + vectorStores.getOptional("vector_stores") + + /** + * Returns the raw JSON value of [objectPermissionId]. + * + * Unlike [objectPermissionId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("object_permission_id") + @ExcludeMissing + fun _objectPermissionId(): JsonField = objectPermissionId + + /** + * Returns the raw JSON value of [agentAccessGroups]. + * + * Unlike [agentAccessGroups], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("agent_access_groups") + @ExcludeMissing + fun _agentAccessGroups(): JsonField> = agentAccessGroups + + /** + * Returns the raw JSON value of [agents]. + * + * Unlike [agents], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("agents") + @ExcludeMissing + fun _agents(): JsonField> = agents + + /** + * Returns the raw JSON value of [mcpAccessGroups]. + * + * Unlike [mcpAccessGroups], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mcp_access_groups") + @ExcludeMissing + fun _mcpAccessGroups(): JsonField> = mcpAccessGroups + + /** + * Returns the raw JSON value of [mcpServers]. + * + * Unlike [mcpServers], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mcp_servers") + @ExcludeMissing + fun _mcpServers(): JsonField> = mcpServers + + /** + * Returns the raw JSON value of [mcpToolPermissions]. + * + * Unlike [mcpToolPermissions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + fun _mcpToolPermissions(): JsonField = mcpToolPermissions + + /** + * Returns the raw JSON value of [vectorStores]. + * + * Unlike [vectorStores], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("vector_stores") + @ExcludeMissing + fun _vectorStores(): JsonField> = vectorStores + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ObjectPermission]. + * + * The following fields are required: + * ```java + * .objectPermissionId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ObjectPermission]. */ + class Builder internal constructor() { + + private var objectPermissionId: JsonField? = null + private var agentAccessGroups: JsonField>? = null + private var agents: JsonField>? = null + private var mcpAccessGroups: JsonField>? = null + private var mcpServers: JsonField>? = null + private var mcpToolPermissions: JsonField = JsonMissing.of() + private var vectorStores: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(objectPermission: ObjectPermission) = apply { + objectPermissionId = objectPermission.objectPermissionId + agentAccessGroups = + objectPermission.agentAccessGroups.map { it.toMutableList() } + agents = objectPermission.agents.map { it.toMutableList() } + mcpAccessGroups = + objectPermission.mcpAccessGroups.map { it.toMutableList() } + mcpServers = objectPermission.mcpServers.map { it.toMutableList() } + mcpToolPermissions = objectPermission.mcpToolPermissions + vectorStores = objectPermission.vectorStores.map { it.toMutableList() } + additionalProperties = objectPermission.additionalProperties.toMutableMap() + } + + fun objectPermissionId(objectPermissionId: String) = + objectPermissionId(JsonField.of(objectPermissionId)) + + /** + * Sets [Builder.objectPermissionId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermissionId] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun objectPermissionId(objectPermissionId: JsonField) = apply { + this.objectPermissionId = objectPermissionId + } + + fun agentAccessGroups(agentAccessGroups: List?) = + agentAccessGroups(JsonField.ofNullable(agentAccessGroups)) + + /** + * Alias for calling [Builder.agentAccessGroups] with + * `agentAccessGroups.orElse(null)`. + */ + fun agentAccessGroups(agentAccessGroups: Optional>) = + agentAccessGroups(agentAccessGroups.getOrNull()) + + /** + * Sets [Builder.agentAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.agentAccessGroups] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun agentAccessGroups(agentAccessGroups: JsonField>) = apply { + this.agentAccessGroups = agentAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agentAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgentAccessGroup(agentAccessGroup: String) = apply { + agentAccessGroups = + (agentAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("agentAccessGroups", it).add(agentAccessGroup) + } + } + + fun agents(agents: List?) = agents(JsonField.ofNullable(agents)) + + /** Alias for calling [Builder.agents] with `agents.orElse(null)`. */ + fun agents(agents: Optional>) = agents(agents.getOrNull()) + + /** + * Sets [Builder.agents] to an arbitrary JSON value. + * + * You should usually call [Builder.agents] with a well-typed `List` + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun agents(agents: JsonField>) = apply { + this.agents = agents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgent(agent: String) = apply { + agents = + (agents ?: JsonField.of(mutableListOf())).also { + checkKnown("agents", it).add(agent) + } + } + + fun mcpAccessGroups(mcpAccessGroups: List?) = + mcpAccessGroups(JsonField.ofNullable(mcpAccessGroups)) + + /** + * Alias for calling [Builder.mcpAccessGroups] with + * `mcpAccessGroups.orElse(null)`. + */ + fun mcpAccessGroups(mcpAccessGroups: Optional>) = + mcpAccessGroups(mcpAccessGroups.getOrNull()) + + /** + * Sets [Builder.mcpAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpAccessGroups] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun mcpAccessGroups(mcpAccessGroups: JsonField>) = apply { + this.mcpAccessGroups = mcpAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpAccessGroup(mcpAccessGroup: String) = apply { + mcpAccessGroups = + (mcpAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpAccessGroups", it).add(mcpAccessGroup) + } + } + + fun mcpServers(mcpServers: List?) = + mcpServers(JsonField.ofNullable(mcpServers)) + + /** Alias for calling [Builder.mcpServers] with `mcpServers.orElse(null)`. */ + fun mcpServers(mcpServers: Optional>) = + mcpServers(mcpServers.getOrNull()) + + /** + * Sets [Builder.mcpServers] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpServers] with a well-typed `List` + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun mcpServers(mcpServers: JsonField>) = apply { + this.mcpServers = mcpServers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpServers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpServer(mcpServer: String) = apply { + mcpServers = + (mcpServers ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpServers", it).add(mcpServer) + } + } + + fun mcpToolPermissions(mcpToolPermissions: McpToolPermissions?) = + mcpToolPermissions(JsonField.ofNullable(mcpToolPermissions)) + + /** + * Alias for calling [Builder.mcpToolPermissions] with + * `mcpToolPermissions.orElse(null)`. + */ + fun mcpToolPermissions(mcpToolPermissions: Optional) = + mcpToolPermissions(mcpToolPermissions.getOrNull()) + + /** + * Sets [Builder.mcpToolPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpToolPermissions] with a well-typed + * [McpToolPermissions] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun mcpToolPermissions(mcpToolPermissions: JsonField) = + apply { + this.mcpToolPermissions = mcpToolPermissions + } + + fun vectorStores(vectorStores: List?) = + vectorStores(JsonField.ofNullable(vectorStores)) + + /** + * Alias for calling [Builder.vectorStores] with `vectorStores.orElse(null)`. + */ + fun vectorStores(vectorStores: Optional>) = + vectorStores(vectorStores.getOrNull()) + + /** + * Sets [Builder.vectorStores] to an arbitrary JSON value. + * + * You should usually call [Builder.vectorStores] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun vectorStores(vectorStores: JsonField>) = apply { + this.vectorStores = vectorStores.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [vectorStores]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addVectorStore(vectorStore: String) = apply { + vectorStores = + (vectorStores ?: JsonField.of(mutableListOf())).also { + checkKnown("vectorStores", it).add(vectorStore) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ObjectPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objectPermissionId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ObjectPermission = + ObjectPermission( + checkRequired("objectPermissionId", objectPermissionId), + (agentAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (agents ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpServers ?: JsonMissing.of()).map { it.toImmutable() }, + mcpToolPermissions, + (vectorStores ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ObjectPermission = apply { + if (validated) { + return@apply + } + + objectPermissionId() + agentAccessGroups() + agents() + mcpAccessGroups() + mcpServers() + mcpToolPermissions().ifPresent { it.validate() } + vectorStores() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (objectPermissionId.asKnown().isPresent) 1 else 0) + + (agentAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (agents.asKnown().getOrNull()?.size ?: 0) + + (mcpAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (mcpServers.asKnown().getOrNull()?.size ?: 0) + + (mcpToolPermissions.asKnown().getOrNull()?.validity() ?: 0) + + (vectorStores.asKnown().getOrNull()?.size ?: 0) + + class McpToolPermissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [McpToolPermissions]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [McpToolPermissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(mcpToolPermissions: McpToolPermissions) = apply { + additionalProperties = + mcpToolPermissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [McpToolPermissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): McpToolPermissions = + McpToolPermissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): McpToolPermissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is McpToolPermissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "McpToolPermissions{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ObjectPermission && + objectPermissionId == other.objectPermissionId && + agentAccessGroups == other.agentAccessGroups && + agents == other.agents && + mcpAccessGroups == other.mcpAccessGroups && + mcpServers == other.mcpServers && + mcpToolPermissions == other.mcpToolPermissions && + vectorStores == other.vectorStores && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + objectPermissionId, + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ObjectPermission{objectPermissionId=$objectPermissionId, agentAccessGroups=$agentAccessGroups, agents=$agents, mcpAccessGroups=$mcpAccessGroups, mcpServers=$mcpServers, mcpToolPermissions=$mcpToolPermissions, vectorStores=$vectorStores, additionalProperties=$additionalProperties}" + } + + class OrganizationMetadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [OrganizationMetadata]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OrganizationMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(organizationMetadata: OrganizationMetadata) = apply { + additionalProperties = + organizationMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [OrganizationMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OrganizationMetadata = + OrganizationMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): OrganizationMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OrganizationMetadata && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "OrganizationMetadata{additionalProperties=$additionalProperties}" + } + + class Permissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Permissions]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Permissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(permissions: Permissions) = apply { + additionalProperties = permissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Permissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Permissions = Permissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Permissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Permissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Permissions{additionalProperties=$additionalProperties}" + } + + class RouterSettings + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RouterSettings]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RouterSettings]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(routerSettings: RouterSettings) = apply { + additionalProperties = routerSettings.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RouterSettings]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RouterSettings = RouterSettings(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): RouterSettings = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RouterSettings && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RouterSettings{additionalProperties=$additionalProperties}" + } + + class RpmLimitPerModel + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RpmLimitPerModel]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RpmLimitPerModel]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(rpmLimitPerModel: RpmLimitPerModel) = apply { + additionalProperties = rpmLimitPerModel.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RpmLimitPerModel]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RpmLimitPerModel = + RpmLimitPerModel(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): RpmLimitPerModel = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RpmLimitPerModel && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RpmLimitPerModel{additionalProperties=$additionalProperties}" + } + + class TeamMetadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [TeamMetadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [TeamMetadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(teamMetadata: TeamMetadata) = apply { + additionalProperties = teamMetadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [TeamMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): TeamMetadata = TeamMetadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): TeamMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TeamMetadata && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "TeamMetadata{additionalProperties=$additionalProperties}" + } + + class TeamModelAliases + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [TeamModelAliases]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [TeamModelAliases]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(teamModelAliases: TeamModelAliases) = apply { + additionalProperties = teamModelAliases.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [TeamModelAliases]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): TeamModelAliases = + TeamModelAliases(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): TeamModelAliases = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TeamModelAliases && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "TeamModelAliases{additionalProperties=$additionalProperties}" + } + + class TpmLimitPerModel + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [TpmLimitPerModel]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [TpmLimitPerModel]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(tpmLimitPerModel: TpmLimitPerModel) = apply { + additionalProperties = tpmLimitPerModel.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [TpmLimitPerModel]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): TpmLimitPerModel = + TpmLimitPerModel(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): TpmLimitPerModel = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TpmLimitPerModel && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "TpmLimitPerModel{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UserApiKeyAuth && + token == other.token && + aliases == other.aliases && + allowedCacheControls == other.allowedCacheControls && + allowedModelRegion == other.allowedModelRegion && + allowedRoutes == other.allowedRoutes && + apiKey == other.apiKey && + autoRotate == other.autoRotate && + blocked == other.blocked && + budgetDuration == other.budgetDuration && + budgetResetAt == other.budgetResetAt && + config == other.config && + createdAt == other.createdAt && + createdBy == other.createdBy && + endUserId == other.endUserId && + endUserMaxBudget == other.endUserMaxBudget && + endUserRpmLimit == other.endUserRpmLimit && + endUserTpmLimit == other.endUserTpmLimit && + expires == other.expires && + keyAlias == other.keyAlias && + keyName == other.keyName && + keyRotationAt == other.keyRotationAt && + lastRefreshedAt == other.lastRefreshedAt && + lastRotationAt == other.lastRotationAt && + litellmBudgetTable == other.litellmBudgetTable && + maxBudget == other.maxBudget && + maxParallelRequests == other.maxParallelRequests && + metadata == other.metadata && + modelMaxBudget == other.modelMaxBudget && + modelSpend == other.modelSpend && + models == other.models && + objectPermission == other.objectPermission && + objectPermissionId == other.objectPermissionId && + orgId == other.orgId && + organizationMaxBudget == other.organizationMaxBudget && + organizationMetadata == other.organizationMetadata && + organizationRpmLimit == other.organizationRpmLimit && + organizationTpmLimit == other.organizationTpmLimit && + parentOtelSpan == other.parentOtelSpan && + permissions == other.permissions && + requestRoute == other.requestRoute && + rotationCount == other.rotationCount && + rotationInterval == other.rotationInterval && + routerSettings == other.routerSettings && + rpmLimit == other.rpmLimit && + rpmLimitPerModel == other.rpmLimitPerModel && + softBudget == other.softBudget && + softBudgetCooldown == other.softBudgetCooldown && + spend == other.spend && + teamAlias == other.teamAlias && + teamBlocked == other.teamBlocked && + teamId == other.teamId && + teamMaxBudget == other.teamMaxBudget && + teamMember == other.teamMember && + teamMemberRpmLimit == other.teamMemberRpmLimit && + teamMemberSpend == other.teamMemberSpend && + teamMemberTpmLimit == other.teamMemberTpmLimit && + teamMetadata == other.teamMetadata && + teamModelAliases == other.teamModelAliases && + teamModels == other.teamModels && + teamObjectPermissionId == other.teamObjectPermissionId && + teamRpmLimit == other.teamRpmLimit && + teamSpend == other.teamSpend && + teamTpmLimit == other.teamTpmLimit && + tpmLimit == other.tpmLimit && + tpmLimitPerModel == other.tpmLimitPerModel && + updatedAt == other.updatedAt && + updatedBy == other.updatedBy && + user == other.user && + userEmail == other.userEmail && + userId == other.userId && + userMaxBudget == other.userMaxBudget && + userRole == other.userRole && + userRpmLimit == other.userRpmLimit && + userSpend == other.userSpend && + userTpmLimit == other.userTpmLimit && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + token, + aliases, + allowedCacheControls, + allowedModelRegion, + allowedRoutes, + apiKey, + autoRotate, + blocked, + budgetDuration, + budgetResetAt, + config, + createdAt, + createdBy, + endUserId, + endUserMaxBudget, + endUserRpmLimit, + endUserTpmLimit, + expires, + keyAlias, + keyName, + keyRotationAt, + lastRefreshedAt, + lastRotationAt, + litellmBudgetTable, + maxBudget, + maxParallelRequests, + metadata, + modelMaxBudget, + modelSpend, + models, + objectPermission, + objectPermissionId, + orgId, + organizationMaxBudget, + organizationMetadata, + organizationRpmLimit, + organizationTpmLimit, + parentOtelSpan, + permissions, + requestRoute, + rotationCount, + rotationInterval, + routerSettings, + rpmLimit, + rpmLimitPerModel, + softBudget, + softBudgetCooldown, + spend, + teamAlias, + teamBlocked, + teamId, + teamMaxBudget, + teamMember, + teamMemberRpmLimit, + teamMemberSpend, + teamMemberTpmLimit, + teamMetadata, + teamModelAliases, + teamModels, + teamObjectPermissionId, + teamRpmLimit, + teamSpend, + teamTpmLimit, + tpmLimit, + tpmLimitPerModel, + updatedAt, + updatedBy, + user, + userEmail, + userId, + userMaxBudget, + userRole, + userRpmLimit, + userSpend, + userTpmLimit, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UserApiKeyAuth{token=$token, aliases=$aliases, allowedCacheControls=$allowedCacheControls, allowedModelRegion=$allowedModelRegion, allowedRoutes=$allowedRoutes, apiKey=$apiKey, autoRotate=$autoRotate, blocked=$blocked, budgetDuration=$budgetDuration, budgetResetAt=$budgetResetAt, config=$config, createdAt=$createdAt, createdBy=$createdBy, endUserId=$endUserId, endUserMaxBudget=$endUserMaxBudget, endUserRpmLimit=$endUserRpmLimit, endUserTpmLimit=$endUserTpmLimit, expires=$expires, keyAlias=$keyAlias, keyName=$keyName, keyRotationAt=$keyRotationAt, lastRefreshedAt=$lastRefreshedAt, lastRotationAt=$lastRotationAt, litellmBudgetTable=$litellmBudgetTable, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelSpend=$modelSpend, models=$models, objectPermission=$objectPermission, objectPermissionId=$objectPermissionId, orgId=$orgId, organizationMaxBudget=$organizationMaxBudget, organizationMetadata=$organizationMetadata, organizationRpmLimit=$organizationRpmLimit, organizationTpmLimit=$organizationTpmLimit, parentOtelSpan=$parentOtelSpan, permissions=$permissions, requestRoute=$requestRoute, rotationCount=$rotationCount, rotationInterval=$rotationInterval, routerSettings=$routerSettings, rpmLimit=$rpmLimit, rpmLimitPerModel=$rpmLimitPerModel, softBudget=$softBudget, softBudgetCooldown=$softBudgetCooldown, spend=$spend, teamAlias=$teamAlias, teamBlocked=$teamBlocked, teamId=$teamId, teamMaxBudget=$teamMaxBudget, teamMember=$teamMember, teamMemberRpmLimit=$teamMemberRpmLimit, teamMemberSpend=$teamMemberSpend, teamMemberTpmLimit=$teamMemberTpmLimit, teamMetadata=$teamMetadata, teamModelAliases=$teamModelAliases, teamModels=$teamModels, teamObjectPermissionId=$teamObjectPermissionId, teamRpmLimit=$teamRpmLimit, teamSpend=$teamSpend, teamTpmLimit=$teamTpmLimit, tpmLimit=$tpmLimit, tpmLimitPerModel=$tpmLimitPerModel, updatedAt=$updatedAt, updatedBy=$updatedBy, user=$user, userEmail=$userEmail, userId=$userId, userMaxBudget=$userMaxBudget, userRole=$userRole, userRpmLimit=$userRpmLimit, userSpend=$userSpend, userTpmLimit=$userTpmLimit, additionalProperties=$additionalProperties}" + } + + /** + * Recording of deleted keys for audit purposes. Mirrors LiteLLM_VerificationToken plus + * metadata captured at deletion time. + */ + class LiteLlmDeletedVerificationToken + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val id: JsonField, + private val token: JsonField, + private val aliases: JsonField, + private val allowedCacheControls: JsonField>, + private val allowedRoutes: JsonField>, + private val autoRotate: JsonField, + private val blocked: JsonField, + private val budgetDuration: JsonField, + private val budgetResetAt: JsonField, + private val config: JsonField, + private val createdAt: JsonField, + private val createdBy: JsonField, + private val deletedAt: JsonField, + private val deletedBy: JsonField, + private val deletedByApiKey: JsonField, + private val expires: JsonField, + private val keyAlias: JsonField, + private val keyName: JsonField, + private val keyRotationAt: JsonField, + private val lastRotationAt: JsonField, + private val litellmBudgetTable: JsonField, + private val litellmChangedBy: JsonField, + private val maxBudget: JsonField, + private val maxParallelRequests: JsonField, + private val metadata: JsonField, + private val modelMaxBudget: JsonField, + private val modelSpend: JsonField, + private val models: JsonField>, + private val objectPermission: JsonField, + private val objectPermissionId: JsonField, + private val orgId: JsonField, + private val permissions: JsonField, + private val rotationCount: JsonField, + private val rotationInterval: JsonField, + private val routerSettings: JsonField, + private val rpmLimit: JsonField, + private val softBudgetCooldown: JsonField, + private val spend: JsonField, + private val teamId: JsonField, + private val tpmLimit: JsonField, + private val updatedAt: JsonField, + private val updatedBy: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("token") @ExcludeMissing token: JsonField = JsonMissing.of(), + @JsonProperty("aliases") + @ExcludeMissing + aliases: JsonField = JsonMissing.of(), + @JsonProperty("allowed_cache_controls") + @ExcludeMissing + allowedCacheControls: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_routes") + @ExcludeMissing + allowedRoutes: JsonField> = JsonMissing.of(), + @JsonProperty("auto_rotate") + @ExcludeMissing + autoRotate: JsonField = JsonMissing.of(), + @JsonProperty("blocked") + @ExcludeMissing + blocked: JsonField = JsonMissing.of(), + @JsonProperty("budget_duration") + @ExcludeMissing + budgetDuration: JsonField = JsonMissing.of(), + @JsonProperty("budget_reset_at") + @ExcludeMissing + budgetResetAt: JsonField = JsonMissing.of(), + @JsonProperty("config") + @ExcludeMissing + config: JsonField = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("created_by") + @ExcludeMissing + createdBy: JsonField = JsonMissing.of(), + @JsonProperty("deleted_at") + @ExcludeMissing + deletedAt: JsonField = JsonMissing.of(), + @JsonProperty("deleted_by") + @ExcludeMissing + deletedBy: JsonField = JsonMissing.of(), + @JsonProperty("deleted_by_api_key") + @ExcludeMissing + deletedByApiKey: JsonField = JsonMissing.of(), + @JsonProperty("expires") + @ExcludeMissing + expires: JsonField = JsonMissing.of(), + @JsonProperty("key_alias") + @ExcludeMissing + keyAlias: JsonField = JsonMissing.of(), + @JsonProperty("key_name") + @ExcludeMissing + keyName: JsonField = JsonMissing.of(), + @JsonProperty("key_rotation_at") + @ExcludeMissing + keyRotationAt: JsonField = JsonMissing.of(), + @JsonProperty("last_rotation_at") + @ExcludeMissing + lastRotationAt: JsonField = JsonMissing.of(), + @JsonProperty("litellm_budget_table") + @ExcludeMissing + litellmBudgetTable: JsonField = JsonMissing.of(), + @JsonProperty("litellm_changed_by") + @ExcludeMissing + litellmChangedBy: JsonField = JsonMissing.of(), + @JsonProperty("max_budget") + @ExcludeMissing + maxBudget: JsonField = JsonMissing.of(), + @JsonProperty("max_parallel_requests") + @ExcludeMissing + maxParallelRequests: JsonField = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), + @JsonProperty("model_max_budget") + @ExcludeMissing + modelMaxBudget: JsonField = JsonMissing.of(), + @JsonProperty("model_spend") + @ExcludeMissing + modelSpend: JsonField = JsonMissing.of(), + @JsonProperty("models") + @ExcludeMissing + models: JsonField> = JsonMissing.of(), + @JsonProperty("object_permission") + @ExcludeMissing + objectPermission: JsonField = JsonMissing.of(), + @JsonProperty("object_permission_id") + @ExcludeMissing + objectPermissionId: JsonField = JsonMissing.of(), + @JsonProperty("org_id") @ExcludeMissing orgId: JsonField = JsonMissing.of(), + @JsonProperty("permissions") + @ExcludeMissing + permissions: JsonField = JsonMissing.of(), + @JsonProperty("rotation_count") + @ExcludeMissing + rotationCount: JsonField = JsonMissing.of(), + @JsonProperty("rotation_interval") + @ExcludeMissing + rotationInterval: JsonField = JsonMissing.of(), + @JsonProperty("router_settings") + @ExcludeMissing + routerSettings: JsonField = JsonMissing.of(), + @JsonProperty("rpm_limit") + @ExcludeMissing + rpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("soft_budget_cooldown") + @ExcludeMissing + softBudgetCooldown: JsonField = JsonMissing.of(), + @JsonProperty("spend") @ExcludeMissing spend: JsonField = JsonMissing.of(), + @JsonProperty("team_id") + @ExcludeMissing + teamId: JsonField = JsonMissing.of(), + @JsonProperty("tpm_limit") + @ExcludeMissing + tpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") + @ExcludeMissing + updatedAt: JsonField = JsonMissing.of(), + @JsonProperty("updated_by") + @ExcludeMissing + updatedBy: JsonField = JsonMissing.of(), + @JsonProperty("user_id") + @ExcludeMissing + userId: JsonField = JsonMissing.of(), + ) : this( + id, + token, + aliases, + allowedCacheControls, + allowedRoutes, + autoRotate, + blocked, + budgetDuration, + budgetResetAt, + config, + createdAt, + createdBy, + deletedAt, + deletedBy, + deletedByApiKey, + expires, + keyAlias, + keyName, + keyRotationAt, + lastRotationAt, + litellmBudgetTable, + litellmChangedBy, + maxBudget, + maxParallelRequests, + metadata, + modelMaxBudget, + modelSpend, + models, + objectPermission, + objectPermissionId, + orgId, + permissions, + rotationCount, + rotationInterval, + routerSettings, + rpmLimit, + softBudgetCooldown, + spend, + teamId, + tpmLimit, + updatedAt, + updatedBy, + userId, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun token(): Optional = token.getOptional("token") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun aliases(): Optional = aliases.getOptional("aliases") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun allowedCacheControls(): Optional> = + allowedCacheControls.getOptional("allowed_cache_controls") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun allowedRoutes(): Optional> = + allowedRoutes.getOptional("allowed_routes") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun autoRotate(): Optional = autoRotate.getOptional("auto_rotate") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun blocked(): Optional = blocked.getOptional("blocked") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun budgetDuration(): Optional = budgetDuration.getOptional("budget_duration") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun budgetResetAt(): Optional = + budgetResetAt.getOptional("budget_reset_at") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun config(): Optional = config.getOptional("config") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("created_at") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun createdBy(): Optional = createdBy.getOptional("created_by") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun deletedAt(): Optional = deletedAt.getOptional("deleted_at") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun deletedBy(): Optional = deletedBy.getOptional("deleted_by") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun deletedByApiKey(): Optional = + deletedByApiKey.getOptional("deleted_by_api_key") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun expires(): Optional = expires.getOptional("expires") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun keyAlias(): Optional = keyAlias.getOptional("key_alias") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun keyName(): Optional = keyName.getOptional("key_name") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun keyRotationAt(): Optional = + keyRotationAt.getOptional("key_rotation_at") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun lastRotationAt(): Optional = + lastRotationAt.getOptional("last_rotation_at") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun litellmBudgetTable(): Optional = + litellmBudgetTable.getOptional("litellm_budget_table") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun litellmChangedBy(): Optional = + litellmChangedBy.getOptional("litellm_changed_by") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun maxBudget(): Optional = maxBudget.getOptional("max_budget") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun maxParallelRequests(): Optional = + maxParallelRequests.getOptional("max_parallel_requests") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun modelMaxBudget(): Optional = + modelMaxBudget.getOptional("model_max_budget") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun modelSpend(): Optional = modelSpend.getOptional("model_spend") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun models(): Optional> = models.getOptional("models") + + /** + * Represents a LiteLLM_ObjectPermissionTable record + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun objectPermission(): Optional = + objectPermission.getOptional("object_permission") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun objectPermissionId(): Optional = + objectPermissionId.getOptional("object_permission_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun orgId(): Optional = orgId.getOptional("org_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun permissions(): Optional = permissions.getOptional("permissions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun rotationCount(): Optional = rotationCount.getOptional("rotation_count") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun rotationInterval(): Optional = + rotationInterval.getOptional("rotation_interval") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun routerSettings(): Optional = + routerSettings.getOptional("router_settings") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun rpmLimit(): Optional = rpmLimit.getOptional("rpm_limit") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun softBudgetCooldown(): Optional = + softBudgetCooldown.getOptional("soft_budget_cooldown") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun spend(): Optional = spend.getOptional("spend") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun teamId(): Optional = teamId.getOptional("team_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun tpmLimit(): Optional = tpmLimit.getOptional("tpm_limit") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun updatedBy(): Optional = updatedBy.getOptional("updated_by") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [token]. + * + * Unlike [token], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("token") @ExcludeMissing fun _token(): JsonField = token + + /** + * Returns the raw JSON value of [aliases]. + * + * Unlike [aliases], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonField = aliases + + /** + * Returns the raw JSON value of [allowedCacheControls]. + * + * Unlike [allowedCacheControls], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("allowed_cache_controls") + @ExcludeMissing + fun _allowedCacheControls(): JsonField> = allowedCacheControls + + /** + * Returns the raw JSON value of [allowedRoutes]. + * + * Unlike [allowedRoutes], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("allowed_routes") + @ExcludeMissing + fun _allowedRoutes(): JsonField> = allowedRoutes + + /** + * Returns the raw JSON value of [autoRotate]. + * + * Unlike [autoRotate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auto_rotate") + @ExcludeMissing + fun _autoRotate(): JsonField = autoRotate + + /** + * Returns the raw JSON value of [blocked]. + * + * Unlike [blocked], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("blocked") @ExcludeMissing fun _blocked(): JsonField = blocked + + /** + * Returns the raw JSON value of [budgetDuration]. + * + * Unlike [budgetDuration], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("budget_duration") + @ExcludeMissing + fun _budgetDuration(): JsonField = budgetDuration + + /** + * Returns the raw JSON value of [budgetResetAt]. + * + * Unlike [budgetResetAt], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("budget_reset_at") + @ExcludeMissing + fun _budgetResetAt(): JsonField = budgetResetAt + + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config") @ExcludeMissing fun _config(): JsonField = config + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [createdBy]. + * + * Unlike [createdBy], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("created_by") + @ExcludeMissing + fun _createdBy(): JsonField = createdBy + + /** + * Returns the raw JSON value of [deletedAt]. * - * Internal User Roles: INTERNAL_USER: can login, view/create/delete their own keys, - * view their spend INTERNAL_USER_VIEW_ONLY: can login, view their own keys, view their - * own spend + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt + + /** + * Returns the raw JSON value of [deletedBy]. * - * Team Roles: TEAM: used for JWT auth + * Unlike [deletedBy], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("deleted_by") + @ExcludeMissing + fun _deletedBy(): JsonField = deletedBy + + /** + * Returns the raw JSON value of [deletedByApiKey]. + * + * Unlike [deletedByApiKey], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("deleted_by_api_key") + @ExcludeMissing + fun _deletedByApiKey(): JsonField = deletedByApiKey + + /** + * Returns the raw JSON value of [expires]. + * + * Unlike [expires], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("expires") @ExcludeMissing fun _expires(): JsonField = expires + + /** + * Returns the raw JSON value of [keyAlias]. + * + * Unlike [keyAlias], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("key_alias") @ExcludeMissing fun _keyAlias(): JsonField = keyAlias + + /** + * Returns the raw JSON value of [keyName]. + * + * Unlike [keyName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("key_name") @ExcludeMissing fun _keyName(): JsonField = keyName + + /** + * Returns the raw JSON value of [keyRotationAt]. + * + * Unlike [keyRotationAt], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("key_rotation_at") + @ExcludeMissing + fun _keyRotationAt(): JsonField = keyRotationAt + + /** + * Returns the raw JSON value of [lastRotationAt]. + * + * Unlike [lastRotationAt], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("last_rotation_at") + @ExcludeMissing + fun _lastRotationAt(): JsonField = lastRotationAt + + /** + * Returns the raw JSON value of [litellmBudgetTable]. + * + * Unlike [litellmBudgetTable], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("litellm_budget_table") + @ExcludeMissing + fun _litellmBudgetTable(): JsonField = litellmBudgetTable + + /** + * Returns the raw JSON value of [litellmChangedBy]. + * + * Unlike [litellmChangedBy], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("litellm_changed_by") + @ExcludeMissing + fun _litellmChangedBy(): JsonField = litellmChangedBy + + /** + * Returns the raw JSON value of [maxBudget]. + * + * Unlike [maxBudget], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("max_budget") + @ExcludeMissing + fun _maxBudget(): JsonField = maxBudget + + /** + * Returns the raw JSON value of [maxParallelRequests]. + * + * Unlike [maxParallelRequests], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("max_parallel_requests") + @ExcludeMissing + fun _maxParallelRequests(): JsonField = maxParallelRequests + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("metadata") + @ExcludeMissing + fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [modelMaxBudget]. + * + * Unlike [modelMaxBudget], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("model_max_budget") + @ExcludeMissing + fun _modelMaxBudget(): JsonField = modelMaxBudget + + /** + * Returns the raw JSON value of [modelSpend]. + * + * Unlike [modelSpend], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("model_spend") + @ExcludeMissing + fun _modelSpend(): JsonField = modelSpend + + /** + * Returns the raw JSON value of [models]. + * + * Unlike [models], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("models") + @ExcludeMissing + fun _models(): JsonField> = models + + /** + * Returns the raw JSON value of [objectPermission]. + * + * Unlike [objectPermission], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("object_permission") + @ExcludeMissing + fun _objectPermission(): JsonField = objectPermission + + /** + * Returns the raw JSON value of [objectPermissionId]. + * + * Unlike [objectPermissionId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("object_permission_id") + @ExcludeMissing + fun _objectPermissionId(): JsonField = objectPermissionId + + /** + * Returns the raw JSON value of [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [permissions]. + * + * Unlike [permissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("permissions") + @ExcludeMissing + fun _permissions(): JsonField = permissions + + /** + * Returns the raw JSON value of [rotationCount]. + * + * Unlike [rotationCount], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("rotation_count") + @ExcludeMissing + fun _rotationCount(): JsonField = rotationCount + + /** + * Returns the raw JSON value of [rotationInterval]. + * + * Unlike [rotationInterval], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("rotation_interval") + @ExcludeMissing + fun _rotationInterval(): JsonField = rotationInterval + + /** + * Returns the raw JSON value of [routerSettings]. + * + * Unlike [routerSettings], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("router_settings") + @ExcludeMissing + fun _routerSettings(): JsonField = routerSettings + + /** + * Returns the raw JSON value of [rpmLimit]. + * + * Unlike [rpmLimit], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("rpm_limit") @ExcludeMissing fun _rpmLimit(): JsonField = rpmLimit + + /** + * Returns the raw JSON value of [softBudgetCooldown]. + * + * Unlike [softBudgetCooldown], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("soft_budget_cooldown") + @ExcludeMissing + fun _softBudgetCooldown(): JsonField = softBudgetCooldown + + /** + * Returns the raw JSON value of [spend]. + * + * Unlike [spend], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("spend") @ExcludeMissing fun _spend(): JsonField = spend + + /** + * Returns the raw JSON value of [teamId]. + * + * Unlike [teamId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("team_id") @ExcludeMissing fun _teamId(): JsonField = teamId + + /** + * Returns the raw JSON value of [tpmLimit]. + * + * Unlike [tpmLimit], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tpm_limit") @ExcludeMissing fun _tpmLimit(): JsonField = tpmLimit + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("updated_at") + @ExcludeMissing + fun _updatedAt(): JsonField = updatedAt + + /** + * Returns the raw JSON value of [updatedBy]. + * + * Unlike [updatedBy], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("updated_by") + @ExcludeMissing + fun _updatedBy(): JsonField = updatedBy + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [LiteLlmDeletedVerificationToken]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LiteLlmDeletedVerificationToken]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var token: JsonField = JsonMissing.of() + private var aliases: JsonField = JsonMissing.of() + private var allowedCacheControls: JsonField>? = null + private var allowedRoutes: JsonField>? = null + private var autoRotate: JsonField = JsonMissing.of() + private var blocked: JsonField = JsonMissing.of() + private var budgetDuration: JsonField = JsonMissing.of() + private var budgetResetAt: JsonField = JsonMissing.of() + private var config: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() + private var createdBy: JsonField = JsonMissing.of() + private var deletedAt: JsonField = JsonMissing.of() + private var deletedBy: JsonField = JsonMissing.of() + private var deletedByApiKey: JsonField = JsonMissing.of() + private var expires: JsonField = JsonMissing.of() + private var keyAlias: JsonField = JsonMissing.of() + private var keyName: JsonField = JsonMissing.of() + private var keyRotationAt: JsonField = JsonMissing.of() + private var lastRotationAt: JsonField = JsonMissing.of() + private var litellmBudgetTable: JsonField = JsonMissing.of() + private var litellmChangedBy: JsonField = JsonMissing.of() + private var maxBudget: JsonField = JsonMissing.of() + private var maxParallelRequests: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var modelMaxBudget: JsonField = JsonMissing.of() + private var modelSpend: JsonField = JsonMissing.of() + private var models: JsonField>? = null + private var objectPermission: JsonField = JsonMissing.of() + private var objectPermissionId: JsonField = JsonMissing.of() + private var orgId: JsonField = JsonMissing.of() + private var permissions: JsonField = JsonMissing.of() + private var rotationCount: JsonField = JsonMissing.of() + private var rotationInterval: JsonField = JsonMissing.of() + private var routerSettings: JsonField = JsonMissing.of() + private var rpmLimit: JsonField = JsonMissing.of() + private var softBudgetCooldown: JsonField = JsonMissing.of() + private var spend: JsonField = JsonMissing.of() + private var teamId: JsonField = JsonMissing.of() + private var tpmLimit: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var updatedBy: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from( + liteLlmDeletedVerificationToken: LiteLlmDeletedVerificationToken + ) = apply { + id = liteLlmDeletedVerificationToken.id + token = liteLlmDeletedVerificationToken.token + aliases = liteLlmDeletedVerificationToken.aliases + allowedCacheControls = + liteLlmDeletedVerificationToken.allowedCacheControls.map { + it.toMutableList() + } + allowedRoutes = + liteLlmDeletedVerificationToken.allowedRoutes.map { it.toMutableList() } + autoRotate = liteLlmDeletedVerificationToken.autoRotate + blocked = liteLlmDeletedVerificationToken.blocked + budgetDuration = liteLlmDeletedVerificationToken.budgetDuration + budgetResetAt = liteLlmDeletedVerificationToken.budgetResetAt + config = liteLlmDeletedVerificationToken.config + createdAt = liteLlmDeletedVerificationToken.createdAt + createdBy = liteLlmDeletedVerificationToken.createdBy + deletedAt = liteLlmDeletedVerificationToken.deletedAt + deletedBy = liteLlmDeletedVerificationToken.deletedBy + deletedByApiKey = liteLlmDeletedVerificationToken.deletedByApiKey + expires = liteLlmDeletedVerificationToken.expires + keyAlias = liteLlmDeletedVerificationToken.keyAlias + keyName = liteLlmDeletedVerificationToken.keyName + keyRotationAt = liteLlmDeletedVerificationToken.keyRotationAt + lastRotationAt = liteLlmDeletedVerificationToken.lastRotationAt + litellmBudgetTable = liteLlmDeletedVerificationToken.litellmBudgetTable + litellmChangedBy = liteLlmDeletedVerificationToken.litellmChangedBy + maxBudget = liteLlmDeletedVerificationToken.maxBudget + maxParallelRequests = liteLlmDeletedVerificationToken.maxParallelRequests + metadata = liteLlmDeletedVerificationToken.metadata + modelMaxBudget = liteLlmDeletedVerificationToken.modelMaxBudget + modelSpend = liteLlmDeletedVerificationToken.modelSpend + models = liteLlmDeletedVerificationToken.models.map { it.toMutableList() } + objectPermission = liteLlmDeletedVerificationToken.objectPermission + objectPermissionId = liteLlmDeletedVerificationToken.objectPermissionId + orgId = liteLlmDeletedVerificationToken.orgId + permissions = liteLlmDeletedVerificationToken.permissions + rotationCount = liteLlmDeletedVerificationToken.rotationCount + rotationInterval = liteLlmDeletedVerificationToken.rotationInterval + routerSettings = liteLlmDeletedVerificationToken.routerSettings + rpmLimit = liteLlmDeletedVerificationToken.rpmLimit + softBudgetCooldown = liteLlmDeletedVerificationToken.softBudgetCooldown + spend = liteLlmDeletedVerificationToken.spend + teamId = liteLlmDeletedVerificationToken.teamId + tpmLimit = liteLlmDeletedVerificationToken.tpmLimit + updatedAt = liteLlmDeletedVerificationToken.updatedAt + updatedBy = liteLlmDeletedVerificationToken.updatedBy + userId = liteLlmDeletedVerificationToken.userId + additionalProperties = + liteLlmDeletedVerificationToken.additionalProperties.toMutableMap() + } + + fun id(id: String?) = id(JsonField.ofNullable(id)) + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + fun token(token: String?) = token(JsonField.ofNullable(token)) + + /** Alias for calling [Builder.token] with `token.orElse(null)`. */ + fun token(token: Optional) = token(token.getOrNull()) + + /** + * Sets [Builder.token] to an arbitrary JSON value. + * + * You should usually call [Builder.token] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun token(token: JsonField) = apply { this.token = token } + + fun aliases(aliases: Aliases) = aliases(JsonField.of(aliases)) + + /** + * Sets [Builder.aliases] to an arbitrary JSON value. + * + * You should usually call [Builder.aliases] with a well-typed [Aliases] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun aliases(aliases: JsonField) = apply { this.aliases = aliases } + + fun allowedCacheControls(allowedCacheControls: List?) = + allowedCacheControls(JsonField.ofNullable(allowedCacheControls)) + + /** + * Alias for calling [Builder.allowedCacheControls] with + * `allowedCacheControls.orElse(null)`. + */ + fun allowedCacheControls(allowedCacheControls: Optional>) = + allowedCacheControls(allowedCacheControls.getOrNull()) + + /** + * Sets [Builder.allowedCacheControls] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedCacheControls] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun allowedCacheControls(allowedCacheControls: JsonField>) = apply { + this.allowedCacheControls = allowedCacheControls.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [allowedCacheControls]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedCacheControl(allowedCacheControl: JsonValue) = apply { + allowedCacheControls = + (allowedCacheControls ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedCacheControls", it).add(allowedCacheControl) + } + } + + fun allowedRoutes(allowedRoutes: List?) = + allowedRoutes(JsonField.ofNullable(allowedRoutes)) + + /** Alias for calling [Builder.allowedRoutes] with `allowedRoutes.orElse(null)`. */ + fun allowedRoutes(allowedRoutes: Optional>) = + allowedRoutes(allowedRoutes.getOrNull()) + + /** + * Sets [Builder.allowedRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedRoutes] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun allowedRoutes(allowedRoutes: JsonField>) = apply { + this.allowedRoutes = allowedRoutes.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [allowedRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedRoute(allowedRoute: JsonValue) = apply { + allowedRoutes = + (allowedRoutes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedRoutes", it).add(allowedRoute) + } + } + + fun autoRotate(autoRotate: Boolean?) = autoRotate(JsonField.ofNullable(autoRotate)) + + /** + * Alias for [Builder.autoRotate]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun autoRotate(autoRotate: Boolean) = autoRotate(autoRotate as Boolean?) + + /** Alias for calling [Builder.autoRotate] with `autoRotate.orElse(null)`. */ + fun autoRotate(autoRotate: Optional) = autoRotate(autoRotate.getOrNull()) + + /** + * Sets [Builder.autoRotate] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRotate] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun autoRotate(autoRotate: JsonField) = apply { + this.autoRotate = autoRotate + } + + fun blocked(blocked: Boolean?) = blocked(JsonField.ofNullable(blocked)) + + /** + * Alias for [Builder.blocked]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun blocked(blocked: Boolean) = blocked(blocked as Boolean?) + + /** Alias for calling [Builder.blocked] with `blocked.orElse(null)`. */ + fun blocked(blocked: Optional) = blocked(blocked.getOrNull()) + + /** + * Sets [Builder.blocked] to an arbitrary JSON value. + * + * You should usually call [Builder.blocked] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun blocked(blocked: JsonField) = apply { this.blocked = blocked } + + fun budgetDuration(budgetDuration: String?) = + budgetDuration(JsonField.ofNullable(budgetDuration)) + + /** + * Alias for calling [Builder.budgetDuration] with `budgetDuration.orElse(null)`. + */ + fun budgetDuration(budgetDuration: Optional) = + budgetDuration(budgetDuration.getOrNull()) + + /** + * Sets [Builder.budgetDuration] to an arbitrary JSON value. + * + * You should usually call [Builder.budgetDuration] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun budgetDuration(budgetDuration: JsonField) = apply { + this.budgetDuration = budgetDuration + } + + fun budgetResetAt(budgetResetAt: OffsetDateTime?) = + budgetResetAt(JsonField.ofNullable(budgetResetAt)) + + /** Alias for calling [Builder.budgetResetAt] with `budgetResetAt.orElse(null)`. */ + fun budgetResetAt(budgetResetAt: Optional) = + budgetResetAt(budgetResetAt.getOrNull()) + + /** + * Sets [Builder.budgetResetAt] to an arbitrary JSON value. + * + * You should usually call [Builder.budgetResetAt] with a well-typed + * [OffsetDateTime] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun budgetResetAt(budgetResetAt: JsonField) = apply { + this.budgetResetAt = budgetResetAt + } + + fun config(config: Config) = config(JsonField.of(config)) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [Config] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun config(config: JsonField) = apply { this.config = config } + + fun createdAt(createdAt: OffsetDateTime?) = + createdAt(JsonField.ofNullable(createdAt)) + + /** Alias for calling [Builder.createdAt] with `createdAt.orElse(null)`. */ + fun createdAt(createdAt: Optional) = + createdAt(createdAt.getOrNull()) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun createdAt(createdAt: JsonField) = apply { + this.createdAt = createdAt + } + + fun createdBy(createdBy: String?) = createdBy(JsonField.ofNullable(createdBy)) + + /** Alias for calling [Builder.createdBy] with `createdBy.orElse(null)`. */ + fun createdBy(createdBy: Optional) = createdBy(createdBy.getOrNull()) + + /** + * Sets [Builder.createdBy] to an arbitrary JSON value. + * + * You should usually call [Builder.createdBy] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun createdBy(createdBy: JsonField) = apply { this.createdBy = createdBy } + + fun deletedAt(deletedAt: OffsetDateTime?) = + deletedAt(JsonField.ofNullable(deletedAt)) + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = + deletedAt(deletedAt.getOrNull()) + + /** + * Sets [Builder.deletedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedAt] with a well-typed [OffsetDateTime] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun deletedAt(deletedAt: JsonField) = apply { + this.deletedAt = deletedAt + } + + fun deletedBy(deletedBy: String?) = deletedBy(JsonField.ofNullable(deletedBy)) + + /** Alias for calling [Builder.deletedBy] with `deletedBy.orElse(null)`. */ + fun deletedBy(deletedBy: Optional) = deletedBy(deletedBy.getOrNull()) + + /** + * Sets [Builder.deletedBy] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedBy] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun deletedBy(deletedBy: JsonField) = apply { this.deletedBy = deletedBy } + + fun deletedByApiKey(deletedByApiKey: String?) = + deletedByApiKey(JsonField.ofNullable(deletedByApiKey)) + + /** + * Alias for calling [Builder.deletedByApiKey] with `deletedByApiKey.orElse(null)`. + */ + fun deletedByApiKey(deletedByApiKey: Optional) = + deletedByApiKey(deletedByApiKey.getOrNull()) + + /** + * Sets [Builder.deletedByApiKey] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedByApiKey] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun deletedByApiKey(deletedByApiKey: JsonField) = apply { + this.deletedByApiKey = deletedByApiKey + } + + fun expires(expires: Expires?) = expires(JsonField.ofNullable(expires)) + + /** Alias for calling [Builder.expires] with `expires.orElse(null)`. */ + fun expires(expires: Optional) = expires(expires.getOrNull()) + + /** + * Sets [Builder.expires] to an arbitrary JSON value. + * + * You should usually call [Builder.expires] with a well-typed [Expires] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun expires(expires: JsonField) = apply { this.expires = expires } + + /** Alias for calling [expires] with `Expires.ofString(string)`. */ + fun expires(string: String) = expires(Expires.ofString(string)) + + /** Alias for calling [expires] with `Expires.ofOffsetDateTime(offsetDateTime)`. */ + fun expires(offsetDateTime: OffsetDateTime) = + expires(Expires.ofOffsetDateTime(offsetDateTime)) + + fun keyAlias(keyAlias: String?) = keyAlias(JsonField.ofNullable(keyAlias)) + + /** Alias for calling [Builder.keyAlias] with `keyAlias.orElse(null)`. */ + fun keyAlias(keyAlias: Optional) = keyAlias(keyAlias.getOrNull()) + + /** + * Sets [Builder.keyAlias] to an arbitrary JSON value. + * + * You should usually call [Builder.keyAlias] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun keyAlias(keyAlias: JsonField) = apply { this.keyAlias = keyAlias } + + fun keyName(keyName: String?) = keyName(JsonField.ofNullable(keyName)) + + /** Alias for calling [Builder.keyName] with `keyName.orElse(null)`. */ + fun keyName(keyName: Optional) = keyName(keyName.getOrNull()) + + /** + * Sets [Builder.keyName] to an arbitrary JSON value. + * + * You should usually call [Builder.keyName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun keyName(keyName: JsonField) = apply { this.keyName = keyName } + + fun keyRotationAt(keyRotationAt: OffsetDateTime?) = + keyRotationAt(JsonField.ofNullable(keyRotationAt)) + + /** Alias for calling [Builder.keyRotationAt] with `keyRotationAt.orElse(null)`. */ + fun keyRotationAt(keyRotationAt: Optional) = + keyRotationAt(keyRotationAt.getOrNull()) + + /** + * Sets [Builder.keyRotationAt] to an arbitrary JSON value. + * + * You should usually call [Builder.keyRotationAt] with a well-typed + * [OffsetDateTime] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun keyRotationAt(keyRotationAt: JsonField) = apply { + this.keyRotationAt = keyRotationAt + } + + fun lastRotationAt(lastRotationAt: OffsetDateTime?) = + lastRotationAt(JsonField.ofNullable(lastRotationAt)) + + /** + * Alias for calling [Builder.lastRotationAt] with `lastRotationAt.orElse(null)`. + */ + fun lastRotationAt(lastRotationAt: Optional) = + lastRotationAt(lastRotationAt.getOrNull()) + + /** + * Sets [Builder.lastRotationAt] to an arbitrary JSON value. + * + * You should usually call [Builder.lastRotationAt] with a well-typed + * [OffsetDateTime] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun lastRotationAt(lastRotationAt: JsonField) = apply { + this.lastRotationAt = lastRotationAt + } + + fun litellmBudgetTable(litellmBudgetTable: LitellmBudgetTable?) = + litellmBudgetTable(JsonField.ofNullable(litellmBudgetTable)) + + /** + * Alias for calling [Builder.litellmBudgetTable] with + * `litellmBudgetTable.orElse(null)`. + */ + fun litellmBudgetTable(litellmBudgetTable: Optional) = + litellmBudgetTable(litellmBudgetTable.getOrNull()) + + /** + * Sets [Builder.litellmBudgetTable] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmBudgetTable] with a well-typed + * [LitellmBudgetTable] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun litellmBudgetTable(litellmBudgetTable: JsonField) = apply { + this.litellmBudgetTable = litellmBudgetTable + } + + fun litellmChangedBy(litellmChangedBy: String?) = + litellmChangedBy(JsonField.ofNullable(litellmChangedBy)) + + /** + * Alias for calling [Builder.litellmChangedBy] with + * `litellmChangedBy.orElse(null)`. + */ + fun litellmChangedBy(litellmChangedBy: Optional) = + litellmChangedBy(litellmChangedBy.getOrNull()) + + /** + * Sets [Builder.litellmChangedBy] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmChangedBy] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun litellmChangedBy(litellmChangedBy: JsonField) = apply { + this.litellmChangedBy = litellmChangedBy + } + + fun maxBudget(maxBudget: Double?) = maxBudget(JsonField.ofNullable(maxBudget)) + + /** + * Alias for [Builder.maxBudget]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxBudget(maxBudget: Double) = maxBudget(maxBudget as Double?) + + /** Alias for calling [Builder.maxBudget] with `maxBudget.orElse(null)`. */ + fun maxBudget(maxBudget: Optional) = maxBudget(maxBudget.getOrNull()) + + /** + * Sets [Builder.maxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.maxBudget] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun maxBudget(maxBudget: JsonField) = apply { this.maxBudget = maxBudget } + + fun maxParallelRequests(maxParallelRequests: Long?) = + maxParallelRequests(JsonField.ofNullable(maxParallelRequests)) + + /** + * Alias for [Builder.maxParallelRequests]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxParallelRequests(maxParallelRequests: Long) = + maxParallelRequests(maxParallelRequests as Long?) + + /** + * Alias for calling [Builder.maxParallelRequests] with + * `maxParallelRequests.orElse(null)`. + */ + fun maxParallelRequests(maxParallelRequests: Optional) = + maxParallelRequests(maxParallelRequests.getOrNull()) + + /** + * Sets [Builder.maxParallelRequests] to an arbitrary JSON value. + * + * You should usually call [Builder.maxParallelRequests] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun maxParallelRequests(maxParallelRequests: JsonField) = apply { + this.maxParallelRequests = maxParallelRequests + } + + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun modelMaxBudget(modelMaxBudget: ModelMaxBudget) = + modelMaxBudget(JsonField.of(modelMaxBudget)) + + /** + * Sets [Builder.modelMaxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.modelMaxBudget] with a well-typed + * [ModelMaxBudget] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun modelMaxBudget(modelMaxBudget: JsonField) = apply { + this.modelMaxBudget = modelMaxBudget + } + + fun modelSpend(modelSpend: ModelSpend) = modelSpend(JsonField.of(modelSpend)) + + /** + * Sets [Builder.modelSpend] to an arbitrary JSON value. + * + * You should usually call [Builder.modelSpend] with a well-typed [ModelSpend] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun modelSpend(modelSpend: JsonField) = apply { + this.modelSpend = modelSpend + } + + fun models(models: List) = models(JsonField.of(models)) + + /** + * Sets [Builder.models] to an arbitrary JSON value. + * + * You should usually call [Builder.models] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun models(models: JsonField>) = apply { + this.models = models.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [models]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addModel(model: JsonValue) = apply { + models = + (models ?: JsonField.of(mutableListOf())).also { + checkKnown("models", it).add(model) + } + } + + /** Represents a LiteLLM_ObjectPermissionTable record */ + fun objectPermission(objectPermission: ObjectPermission?) = + objectPermission(JsonField.ofNullable(objectPermission)) + + /** + * Alias for calling [Builder.objectPermission] with + * `objectPermission.orElse(null)`. + */ + fun objectPermission(objectPermission: Optional) = + objectPermission(objectPermission.getOrNull()) + + /** + * Sets [Builder.objectPermission] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermission] with a well-typed + * [ObjectPermission] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun objectPermission(objectPermission: JsonField) = apply { + this.objectPermission = objectPermission + } + + fun objectPermissionId(objectPermissionId: String?) = + objectPermissionId(JsonField.ofNullable(objectPermissionId)) + + /** + * Alias for calling [Builder.objectPermissionId] with + * `objectPermissionId.orElse(null)`. + */ + fun objectPermissionId(objectPermissionId: Optional) = + objectPermissionId(objectPermissionId.getOrNull()) + + /** + * Sets [Builder.objectPermissionId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermissionId] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun objectPermissionId(objectPermissionId: JsonField) = apply { + this.objectPermissionId = objectPermissionId + } + + fun orgId(orgId: String?) = orgId(JsonField.ofNullable(orgId)) + + /** Alias for calling [Builder.orgId] with `orgId.orElse(null)`. */ + fun orgId(orgId: Optional) = orgId(orgId.getOrNull()) + + /** + * Sets [Builder.orgId] to an arbitrary JSON value. + * + * You should usually call [Builder.orgId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun orgId(orgId: JsonField) = apply { this.orgId = orgId } + + fun permissions(permissions: Permissions) = permissions(JsonField.of(permissions)) + + /** + * Sets [Builder.permissions] to an arbitrary JSON value. + * + * You should usually call [Builder.permissions] with a well-typed [Permissions] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun permissions(permissions: JsonField) = apply { + this.permissions = permissions + } + + fun rotationCount(rotationCount: Long?) = + rotationCount(JsonField.ofNullable(rotationCount)) + + /** + * Alias for [Builder.rotationCount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun rotationCount(rotationCount: Long) = rotationCount(rotationCount as Long?) + + /** Alias for calling [Builder.rotationCount] with `rotationCount.orElse(null)`. */ + fun rotationCount(rotationCount: Optional) = + rotationCount(rotationCount.getOrNull()) + + /** + * Sets [Builder.rotationCount] to an arbitrary JSON value. + * + * You should usually call [Builder.rotationCount] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun rotationCount(rotationCount: JsonField) = apply { + this.rotationCount = rotationCount + } + + fun rotationInterval(rotationInterval: String?) = + rotationInterval(JsonField.ofNullable(rotationInterval)) + + /** + * Alias for calling [Builder.rotationInterval] with + * `rotationInterval.orElse(null)`. + */ + fun rotationInterval(rotationInterval: Optional) = + rotationInterval(rotationInterval.getOrNull()) + + /** + * Sets [Builder.rotationInterval] to an arbitrary JSON value. + * + * You should usually call [Builder.rotationInterval] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun rotationInterval(rotationInterval: JsonField) = apply { + this.rotationInterval = rotationInterval + } + + fun routerSettings(routerSettings: RouterSettings?) = + routerSettings(JsonField.ofNullable(routerSettings)) + + /** + * Alias for calling [Builder.routerSettings] with `routerSettings.orElse(null)`. + */ + fun routerSettings(routerSettings: Optional) = + routerSettings(routerSettings.getOrNull()) + + /** + * Sets [Builder.routerSettings] to an arbitrary JSON value. + * + * You should usually call [Builder.routerSettings] with a well-typed + * [RouterSettings] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun routerSettings(routerSettings: JsonField) = apply { + this.routerSettings = routerSettings + } + + fun rpmLimit(rpmLimit: Long?) = rpmLimit(JsonField.ofNullable(rpmLimit)) + + /** + * Alias for [Builder.rpmLimit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun rpmLimit(rpmLimit: Long) = rpmLimit(rpmLimit as Long?) + + /** Alias for calling [Builder.rpmLimit] with `rpmLimit.orElse(null)`. */ + fun rpmLimit(rpmLimit: Optional) = rpmLimit(rpmLimit.getOrNull()) + + /** + * Sets [Builder.rpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.rpmLimit] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun rpmLimit(rpmLimit: JsonField) = apply { this.rpmLimit = rpmLimit } + + fun softBudgetCooldown(softBudgetCooldown: Boolean) = + softBudgetCooldown(JsonField.of(softBudgetCooldown)) + + /** + * Sets [Builder.softBudgetCooldown] to an arbitrary JSON value. + * + * You should usually call [Builder.softBudgetCooldown] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun softBudgetCooldown(softBudgetCooldown: JsonField) = apply { + this.softBudgetCooldown = softBudgetCooldown + } + + fun spend(spend: Double) = spend(JsonField.of(spend)) + + /** + * Sets [Builder.spend] to an arbitrary JSON value. + * + * You should usually call [Builder.spend] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spend(spend: JsonField) = apply { this.spend = spend } + + fun teamId(teamId: String?) = teamId(JsonField.ofNullable(teamId)) + + /** Alias for calling [Builder.teamId] with `teamId.orElse(null)`. */ + fun teamId(teamId: Optional) = teamId(teamId.getOrNull()) + + /** + * Sets [Builder.teamId] to an arbitrary JSON value. + * + * You should usually call [Builder.teamId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun teamId(teamId: JsonField) = apply { this.teamId = teamId } + + fun tpmLimit(tpmLimit: Long?) = tpmLimit(JsonField.ofNullable(tpmLimit)) + + /** + * Alias for [Builder.tpmLimit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun tpmLimit(tpmLimit: Long) = tpmLimit(tpmLimit as Long?) + + /** Alias for calling [Builder.tpmLimit] with `tpmLimit.orElse(null)`. */ + fun tpmLimit(tpmLimit: Optional) = tpmLimit(tpmLimit.getOrNull()) + + /** + * Sets [Builder.tpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.tpmLimit] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun tpmLimit(tpmLimit: JsonField) = apply { this.tpmLimit = tpmLimit } + + fun updatedAt(updatedAt: OffsetDateTime?) = + updatedAt(JsonField.ofNullable(updatedAt)) + + /** Alias for calling [Builder.updatedAt] with `updatedAt.orElse(null)`. */ + fun updatedAt(updatedAt: Optional) = + updatedAt(updatedAt.getOrNull()) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [OffsetDateTime] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun updatedAt(updatedAt: JsonField) = apply { + this.updatedAt = updatedAt + } + + fun updatedBy(updatedBy: String?) = updatedBy(JsonField.ofNullable(updatedBy)) + + /** Alias for calling [Builder.updatedBy] with `updatedBy.orElse(null)`. */ + fun updatedBy(updatedBy: Optional) = updatedBy(updatedBy.getOrNull()) + + /** + * Sets [Builder.updatedBy] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedBy] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun updatedBy(updatedBy: JsonField) = apply { this.updatedBy = updatedBy } + + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [LiteLlmDeletedVerificationToken]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): LiteLlmDeletedVerificationToken = + LiteLlmDeletedVerificationToken( + id, + token, + aliases, + (allowedCacheControls ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedRoutes ?: JsonMissing.of()).map { it.toImmutable() }, + autoRotate, + blocked, + budgetDuration, + budgetResetAt, + config, + createdAt, + createdBy, + deletedAt, + deletedBy, + deletedByApiKey, + expires, + keyAlias, + keyName, + keyRotationAt, + lastRotationAt, + litellmBudgetTable, + litellmChangedBy, + maxBudget, + maxParallelRequests, + metadata, + modelMaxBudget, + modelSpend, + (models ?: JsonMissing.of()).map { it.toImmutable() }, + objectPermission, + objectPermissionId, + orgId, + permissions, + rotationCount, + rotationInterval, + routerSettings, + rpmLimit, + softBudgetCooldown, + spend, + teamId, + tpmLimit, + updatedAt, + updatedBy, + userId, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): LiteLlmDeletedVerificationToken = apply { + if (validated) { + return@apply + } + + id() + token() + aliases().ifPresent { it.validate() } + allowedCacheControls() + allowedRoutes() + autoRotate() + blocked() + budgetDuration() + budgetResetAt() + config().ifPresent { it.validate() } + createdAt() + createdBy() + deletedAt() + deletedBy() + deletedByApiKey() + expires().ifPresent { it.validate() } + keyAlias() + keyName() + keyRotationAt() + lastRotationAt() + litellmBudgetTable().ifPresent { it.validate() } + litellmChangedBy() + maxBudget() + maxParallelRequests() + metadata().ifPresent { it.validate() } + modelMaxBudget().ifPresent { it.validate() } + modelSpend().ifPresent { it.validate() } + models() + objectPermission().ifPresent { it.validate() } + objectPermissionId() + orgId() + permissions().ifPresent { it.validate() } + rotationCount() + rotationInterval() + routerSettings().ifPresent { it.validate() } + rpmLimit() + softBudgetCooldown() + spend() + teamId() + tpmLimit() + updatedAt() + updatedBy() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * Customer Roles: CUSTOMER: External users -> these are customers + * Used for best match union deserialization. */ - class UserRole @JsonCreator private constructor(private val value: JsonField) : - Enum { + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (token.asKnown().isPresent) 1 else 0) + + (aliases.asKnown().getOrNull()?.validity() ?: 0) + + (allowedCacheControls.asKnown().getOrNull()?.size ?: 0) + + (allowedRoutes.asKnown().getOrNull()?.size ?: 0) + + (if (autoRotate.asKnown().isPresent) 1 else 0) + + (if (blocked.asKnown().isPresent) 1 else 0) + + (if (budgetDuration.asKnown().isPresent) 1 else 0) + + (if (budgetResetAt.asKnown().isPresent) 1 else 0) + + (config.asKnown().getOrNull()?.validity() ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (createdBy.asKnown().isPresent) 1 else 0) + + (if (deletedAt.asKnown().isPresent) 1 else 0) + + (if (deletedBy.asKnown().isPresent) 1 else 0) + + (if (deletedByApiKey.asKnown().isPresent) 1 else 0) + + (expires.asKnown().getOrNull()?.validity() ?: 0) + + (if (keyAlias.asKnown().isPresent) 1 else 0) + + (if (keyName.asKnown().isPresent) 1 else 0) + + (if (keyRotationAt.asKnown().isPresent) 1 else 0) + + (if (lastRotationAt.asKnown().isPresent) 1 else 0) + + (litellmBudgetTable.asKnown().getOrNull()?.validity() ?: 0) + + (if (litellmChangedBy.asKnown().isPresent) 1 else 0) + + (if (maxBudget.asKnown().isPresent) 1 else 0) + + (if (maxParallelRequests.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (modelMaxBudget.asKnown().getOrNull()?.validity() ?: 0) + + (modelSpend.asKnown().getOrNull()?.validity() ?: 0) + + (models.asKnown().getOrNull()?.size ?: 0) + + (objectPermission.asKnown().getOrNull()?.validity() ?: 0) + + (if (objectPermissionId.asKnown().isPresent) 1 else 0) + + (if (orgId.asKnown().isPresent) 1 else 0) + + (permissions.asKnown().getOrNull()?.validity() ?: 0) + + (if (rotationCount.asKnown().isPresent) 1 else 0) + + (if (rotationInterval.asKnown().isPresent) 1 else 0) + + (routerSettings.asKnown().getOrNull()?.validity() ?: 0) + + (if (rpmLimit.asKnown().isPresent) 1 else 0) + + (if (softBudgetCooldown.asKnown().isPresent) 1 else 0) + + (if (spend.asKnown().isPresent) 1 else 0) + + (if (teamId.asKnown().isPresent) 1 else 0) + + (if (tpmLimit.asKnown().isPresent) 1 else 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + (if (updatedBy.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + class Aliases + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Aliases]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Aliases]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aliases: Aliases) = apply { + additionalProperties = aliases.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Aliases]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Aliases = Aliases(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Aliases = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Aliases && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Aliases{additionalProperties=$additionalProperties}" + } + + class Config + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Config]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Config]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(config: Config) = apply { + additionalProperties = config.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Config]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Config = Config(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Config = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Config && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Config{additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = Expires.Deserializer::class) + @JsonSerialize(using = Expires.Serializer::class) + class Expires + private constructor( + private val string: String? = null, + private val offsetDateTime: OffsetDateTime? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun offsetDateTime(): Optional = Optional.ofNullable(offsetDateTime) + + fun isString(): Boolean = string != null + + fun isOffsetDateTime(): Boolean = offsetDateTime != null + + fun asString(): String = string.getOrThrow("string") + + fun asOffsetDateTime(): OffsetDateTime = offsetDateTime.getOrThrow("offsetDateTime") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + offsetDateTime != null -> visitor.visitOffsetDateTime(offsetDateTime) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Expires = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitOffsetDateTime(offsetDateTime: OffsetDateTime) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 + + override fun visitOffsetDateTime(offsetDateTime: OffsetDateTime) = 1 + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Expires && + string == other.string && + offsetDateTime == other.offsetDateTime + } + + override fun hashCode(): Int = Objects.hash(string, offsetDateTime) + + override fun toString(): String = + when { + string != null -> "Expires{string=$string}" + offsetDateTime != null -> "Expires{offsetDateTime=$offsetDateTime}" + _json != null -> "Expires{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Expires") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Expires(string = string) + + @JvmStatic + fun ofOffsetDateTime(offsetDateTime: OffsetDateTime) = + Expires(offsetDateTime = offsetDateTime) + } + + /** + * An interface that defines how to map each variant of [Expires] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitOffsetDateTime(offsetDateTime: OffsetDateTime): T + + /** + * Maps an unknown variant of [Expires] to a value of type [T]. + * + * An instance of [Expires] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Expires: $json") + } + } + + internal class Deserializer : BaseDeserializer(Expires::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Expires { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Expires(offsetDateTime = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + Expires(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing from + // boolean). + 0 -> Expires(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use + // the first completely valid match, or simply the first match if none + // are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : BaseSerializer(Expires::class) { + + override fun serialize( + value: Expires, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.offsetDateTime != null -> + generator.writeObject(value.offsetDateTime) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Expires") + } + } + } + } + + class LitellmBudgetTable + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [LitellmBudgetTable]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LitellmBudgetTable]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(litellmBudgetTable: LitellmBudgetTable) = apply { + additionalProperties = + litellmBudgetTable.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [LitellmBudgetTable]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): LitellmBudgetTable = + LitellmBudgetTable(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): LitellmBudgetTable = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is LitellmBudgetTable && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "LitellmBudgetTable{additionalProperties=$additionalProperties}" + } + + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + class ModelMaxBudget + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ModelMaxBudget]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelMaxBudget]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelMaxBudget: ModelMaxBudget) = apply { + additionalProperties = modelMaxBudget.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelMaxBudget]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelMaxBudget = ModelMaxBudget(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelMaxBudget = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelMaxBudget && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ModelMaxBudget{additionalProperties=$additionalProperties}" + } + + class ModelSpend + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelSpend]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelSpend]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelSpend: ModelSpend) = apply { + additionalProperties = modelSpend.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelSpend]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelSpend = ModelSpend(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelSpend = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelSpend && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelSpend{additionalProperties=$additionalProperties}" + } + + /** Represents a LiteLLM_ObjectPermissionTable record */ + class ObjectPermission + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val objectPermissionId: JsonField, + private val agentAccessGroups: JsonField>, + private val agents: JsonField>, + private val mcpAccessGroups: JsonField>, + private val mcpServers: JsonField>, + private val mcpToolPermissions: JsonField, + private val vectorStores: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("object_permission_id") + @ExcludeMissing + objectPermissionId: JsonField = JsonMissing.of(), + @JsonProperty("agent_access_groups") + @ExcludeMissing + agentAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("agents") + @ExcludeMissing + agents: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_access_groups") + @ExcludeMissing + mcpAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_servers") + @ExcludeMissing + mcpServers: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + mcpToolPermissions: JsonField = JsonMissing.of(), + @JsonProperty("vector_stores") + @ExcludeMissing + vectorStores: JsonField> = JsonMissing.of(), + ) : this( + objectPermissionId, + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun objectPermissionId(): String = + objectPermissionId.getRequired("object_permission_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun agentAccessGroups(): Optional> = + agentAccessGroups.getOptional("agent_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun agents(): Optional> = agents.getOptional("agents") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun mcpAccessGroups(): Optional> = + mcpAccessGroups.getOptional("mcp_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun mcpServers(): Optional> = mcpServers.getOptional("mcp_servers") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun mcpToolPermissions(): Optional = + mcpToolPermissions.getOptional("mcp_tool_permissions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun vectorStores(): Optional> = + vectorStores.getOptional("vector_stores") + + /** + * Returns the raw JSON value of [objectPermissionId]. + * + * Unlike [objectPermissionId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("object_permission_id") + @ExcludeMissing + fun _objectPermissionId(): JsonField = objectPermissionId + + /** + * Returns the raw JSON value of [agentAccessGroups]. + * + * Unlike [agentAccessGroups], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("agent_access_groups") + @ExcludeMissing + fun _agentAccessGroups(): JsonField> = agentAccessGroups + + /** + * Returns the raw JSON value of [agents]. + * + * Unlike [agents], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("agents") + @ExcludeMissing + fun _agents(): JsonField> = agents + + /** + * Returns the raw JSON value of [mcpAccessGroups]. + * + * Unlike [mcpAccessGroups], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mcp_access_groups") + @ExcludeMissing + fun _mcpAccessGroups(): JsonField> = mcpAccessGroups + + /** + * Returns the raw JSON value of [mcpServers]. + * + * Unlike [mcpServers], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mcp_servers") + @ExcludeMissing + fun _mcpServers(): JsonField> = mcpServers + + /** + * Returns the raw JSON value of [mcpToolPermissions]. + * + * Unlike [mcpToolPermissions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + fun _mcpToolPermissions(): JsonField = mcpToolPermissions + + /** + * Returns the raw JSON value of [vectorStores]. + * + * Unlike [vectorStores], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("vector_stores") + @ExcludeMissing + fun _vectorStores(): JsonField> = vectorStores + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ObjectPermission]. + * + * The following fields are required: + * ```java + * .objectPermissionId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ObjectPermission]. */ + class Builder internal constructor() { + + private var objectPermissionId: JsonField? = null + private var agentAccessGroups: JsonField>? = null + private var agents: JsonField>? = null + private var mcpAccessGroups: JsonField>? = null + private var mcpServers: JsonField>? = null + private var mcpToolPermissions: JsonField = JsonMissing.of() + private var vectorStores: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(objectPermission: ObjectPermission) = apply { + objectPermissionId = objectPermission.objectPermissionId + agentAccessGroups = + objectPermission.agentAccessGroups.map { it.toMutableList() } + agents = objectPermission.agents.map { it.toMutableList() } + mcpAccessGroups = + objectPermission.mcpAccessGroups.map { it.toMutableList() } + mcpServers = objectPermission.mcpServers.map { it.toMutableList() } + mcpToolPermissions = objectPermission.mcpToolPermissions + vectorStores = objectPermission.vectorStores.map { it.toMutableList() } + additionalProperties = objectPermission.additionalProperties.toMutableMap() + } + + fun objectPermissionId(objectPermissionId: String) = + objectPermissionId(JsonField.of(objectPermissionId)) + + /** + * Sets [Builder.objectPermissionId] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermissionId] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun objectPermissionId(objectPermissionId: JsonField) = apply { + this.objectPermissionId = objectPermissionId + } + + fun agentAccessGroups(agentAccessGroups: List?) = + agentAccessGroups(JsonField.ofNullable(agentAccessGroups)) + + /** + * Alias for calling [Builder.agentAccessGroups] with + * `agentAccessGroups.orElse(null)`. + */ + fun agentAccessGroups(agentAccessGroups: Optional>) = + agentAccessGroups(agentAccessGroups.getOrNull()) + + /** + * Sets [Builder.agentAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.agentAccessGroups] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun agentAccessGroups(agentAccessGroups: JsonField>) = apply { + this.agentAccessGroups = agentAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agentAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgentAccessGroup(agentAccessGroup: String) = apply { + agentAccessGroups = + (agentAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("agentAccessGroups", it).add(agentAccessGroup) + } + } + + fun agents(agents: List?) = agents(JsonField.ofNullable(agents)) + + /** Alias for calling [Builder.agents] with `agents.orElse(null)`. */ + fun agents(agents: Optional>) = agents(agents.getOrNull()) + + /** + * Sets [Builder.agents] to an arbitrary JSON value. + * + * You should usually call [Builder.agents] with a well-typed `List` + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun agents(agents: JsonField>) = apply { + this.agents = agents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgent(agent: String) = apply { + agents = + (agents ?: JsonField.of(mutableListOf())).also { + checkKnown("agents", it).add(agent) + } + } + + fun mcpAccessGroups(mcpAccessGroups: List?) = + mcpAccessGroups(JsonField.ofNullable(mcpAccessGroups)) + + /** + * Alias for calling [Builder.mcpAccessGroups] with + * `mcpAccessGroups.orElse(null)`. + */ + fun mcpAccessGroups(mcpAccessGroups: Optional>) = + mcpAccessGroups(mcpAccessGroups.getOrNull()) + + /** + * Sets [Builder.mcpAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpAccessGroups] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun mcpAccessGroups(mcpAccessGroups: JsonField>) = apply { + this.mcpAccessGroups = mcpAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpAccessGroup(mcpAccessGroup: String) = apply { + mcpAccessGroups = + (mcpAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpAccessGroups", it).add(mcpAccessGroup) + } + } + + fun mcpServers(mcpServers: List?) = + mcpServers(JsonField.ofNullable(mcpServers)) + + /** Alias for calling [Builder.mcpServers] with `mcpServers.orElse(null)`. */ + fun mcpServers(mcpServers: Optional>) = + mcpServers(mcpServers.getOrNull()) + + /** + * Sets [Builder.mcpServers] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpServers] with a well-typed `List` + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun mcpServers(mcpServers: JsonField>) = apply { + this.mcpServers = mcpServers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpServers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpServer(mcpServer: String) = apply { + mcpServers = + (mcpServers ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpServers", it).add(mcpServer) + } + } + + fun mcpToolPermissions(mcpToolPermissions: McpToolPermissions?) = + mcpToolPermissions(JsonField.ofNullable(mcpToolPermissions)) + + /** + * Alias for calling [Builder.mcpToolPermissions] with + * `mcpToolPermissions.orElse(null)`. + */ + fun mcpToolPermissions(mcpToolPermissions: Optional) = + mcpToolPermissions(mcpToolPermissions.getOrNull()) + + /** + * Sets [Builder.mcpToolPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpToolPermissions] with a well-typed + * [McpToolPermissions] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun mcpToolPermissions(mcpToolPermissions: JsonField) = + apply { + this.mcpToolPermissions = mcpToolPermissions + } + + fun vectorStores(vectorStores: List?) = + vectorStores(JsonField.ofNullable(vectorStores)) + + /** + * Alias for calling [Builder.vectorStores] with `vectorStores.orElse(null)`. + */ + fun vectorStores(vectorStores: Optional>) = + vectorStores(vectorStores.getOrNull()) + + /** + * Sets [Builder.vectorStores] to an arbitrary JSON value. + * + * You should usually call [Builder.vectorStores] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun vectorStores(vectorStores: JsonField>) = apply { + this.vectorStores = vectorStores.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [vectorStores]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addVectorStore(vectorStore: String) = apply { + vectorStores = + (vectorStores ?: JsonField.of(mutableListOf())).also { + checkKnown("vectorStores", it).add(vectorStore) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ObjectPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .objectPermissionId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ObjectPermission = + ObjectPermission( + checkRequired("objectPermissionId", objectPermissionId), + (agentAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (agents ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpServers ?: JsonMissing.of()).map { it.toImmutable() }, + mcpToolPermissions, + (vectorStores ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ObjectPermission = apply { + if (validated) { + return@apply + } + + objectPermissionId() + agentAccessGroups() + agents() + mcpAccessGroups() + mcpServers() + mcpToolPermissions().ifPresent { it.validate() } + vectorStores() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } /** - * Returns this class instance's raw value. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * This is usually only useful if this instance was deserialized from data that - * doesn't match any known member, and you want to know that value. For example, if - * the SDK is on an older version than the API, then the API may respond with new - * members that the SDK is unaware of. + * Used for best match union deserialization. */ - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + @JvmSynthetic + internal fun validity(): Int = + (if (objectPermissionId.asKnown().isPresent) 1 else 0) + + (agentAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (agents.asKnown().getOrNull()?.size ?: 0) + + (mcpAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (mcpServers.asKnown().getOrNull()?.size ?: 0) + + (mcpToolPermissions.asKnown().getOrNull()?.validity() ?: 0) + + (vectorStores.asKnown().getOrNull()?.size ?: 0) + + class McpToolPermissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [McpToolPermissions]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [McpToolPermissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(mcpToolPermissions: McpToolPermissions) = apply { + additionalProperties = + mcpToolPermissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [McpToolPermissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): McpToolPermissions = + McpToolPermissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): McpToolPermissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is McpToolPermissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "McpToolPermissions{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ObjectPermission && + objectPermissionId == other.objectPermissionId && + agentAccessGroups == other.agentAccessGroups && + agents == other.agents && + mcpAccessGroups == other.mcpAccessGroups && + mcpServers == other.mcpServers && + mcpToolPermissions == other.mcpToolPermissions && + vectorStores == other.vectorStores && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + objectPermissionId, + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ObjectPermission{objectPermissionId=$objectPermissionId, agentAccessGroups=$agentAccessGroups, agents=$agents, mcpAccessGroups=$mcpAccessGroups, mcpServers=$mcpServers, mcpToolPermissions=$mcpToolPermissions, vectorStores=$vectorStores, additionalProperties=$additionalProperties}" + } + + class Permissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) companion object { - @JvmField val PROXY_ADMIN = of("proxy_admin") + /** Returns a mutable builder for constructing an instance of [Permissions]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Permissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() - @JvmField val PROXY_ADMIN_VIEWER = of("proxy_admin_viewer") + @JvmSynthetic + internal fun from(permissions: Permissions) = apply { + additionalProperties = permissions.additionalProperties.toMutableMap() + } - @JvmField val ORG_ADMIN = of("org_admin") + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - @JvmField val INTERNAL_USER = of("internal_user") + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - @JvmField val INTERNAL_USER_VIEWER = of("internal_user_viewer") + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } - @JvmField val TEAM = of("team") + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } - @JvmField val CUSTOMER = of("customer") + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - @JvmStatic fun of(value: String) = UserRole(JsonField.of(value)) + /** + * Returns an immutable instance of [Permissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Permissions = Permissions(additionalProperties.toImmutable()) } - /** An enum containing [UserRole]'s known values. */ - enum class Known { - PROXY_ADMIN, - PROXY_ADMIN_VIEWER, - ORG_ADMIN, - INTERNAL_USER, - INTERNAL_USER_VIEWER, - TEAM, - CUSTOMER, + private var validated: Boolean = false + + fun validate(): Permissions = apply { + if (validated) { + return@apply + } + + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + /** - * An enum containing [UserRole]'s known values, as well as an [_UNKNOWN] member. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * An instance of [UserRole] can contain an unknown value in a couple of cases: - * - It was deserialized from data that doesn't match any known member. For example, - * if the SDK is on an older version than the API, then the API may respond with - * new members that the SDK is unaware of. - * - It was constructed with an arbitrary value using the [of] method. + * Used for best match union deserialization. */ - enum class Value { - PROXY_ADMIN, - PROXY_ADMIN_VIEWER, - ORG_ADMIN, - INTERNAL_USER, - INTERNAL_USER_VIEWER, - TEAM, - CUSTOMER, + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Permissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Permissions{additionalProperties=$additionalProperties}" + } + + class RouterSettings + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + /** - * An enum member indicating that [UserRole] was instantiated with an unknown - * value. + * Returns a mutable builder for constructing an instance of [RouterSettings]. */ - _UNKNOWN, + @JvmStatic fun builder() = Builder() } - /** - * Returns an enum member corresponding to this class instance's value, or - * [Value._UNKNOWN] if the class was instantiated with an unknown value. - * - * Use the [known] method instead if you're certain the value is always known or if - * you want to throw for the unknown case. - */ - fun value(): Value = - when (this) { - PROXY_ADMIN -> Value.PROXY_ADMIN - PROXY_ADMIN_VIEWER -> Value.PROXY_ADMIN_VIEWER - ORG_ADMIN -> Value.ORG_ADMIN - INTERNAL_USER -> Value.INTERNAL_USER - INTERNAL_USER_VIEWER -> Value.INTERNAL_USER_VIEWER - TEAM -> Value.TEAM - CUSTOMER -> Value.CUSTOMER - else -> Value._UNKNOWN + /** A builder for [RouterSettings]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(routerSettings: RouterSettings) = apply { + additionalProperties = routerSettings.additionalProperties.toMutableMap() } - /** - * Returns an enum member corresponding to this class instance's value. - * - * Use the [value] method instead if you're uncertain the value is always known and - * don't want to throw for the unknown case. - * - * @throws HanzoInvalidDataException if this class instance's value is a not a known - * member. - */ - fun known(): Known = - when (this) { - PROXY_ADMIN -> Known.PROXY_ADMIN - PROXY_ADMIN_VIEWER -> Known.PROXY_ADMIN_VIEWER - ORG_ADMIN -> Known.ORG_ADMIN - INTERNAL_USER -> Known.INTERNAL_USER - INTERNAL_USER_VIEWER -> Known.INTERNAL_USER_VIEWER - TEAM -> Known.TEAM - CUSTOMER -> Known.CUSTOMER - else -> throw HanzoInvalidDataException("Unknown UserRole: $value") + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RouterSettings]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RouterSettings = RouterSettings(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): RouterSettings = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false } /** - * Returns this class instance's primitive wire representation. - * - * This differs from the [toString] method because that method is primarily for - * debugging and generally doesn't throw. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * @throws HanzoInvalidDataException if this class instance's value does not have - * the expected primitive type. + * Used for best match union deserialization. */ - fun asString(): String = - _value().asString().orElseThrow { - HanzoInvalidDataException("Value is not a String") + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() } override fun equals(other: Any?): Boolean { @@ -3232,12 +10228,16 @@ private constructor( return true } - return /* spotless:off */ other is UserRole && value == other.value /* spotless:on */ + return other is RouterSettings && + additionalProperties == other.additionalProperties } - override fun hashCode() = value.hashCode() + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - override fun toString() = value.toString() + override fun hashCode(): Int = hashCode + + override fun toString() = + "RouterSettings{additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { @@ -3245,17 +10245,106 @@ private constructor( return true } - return /* spotless:off */ other is UserApiKeyAuth && token == other.token && aliases == other.aliases && allowedCacheControls == other.allowedCacheControls && allowedModelRegion == other.allowedModelRegion && apiKey == other.apiKey && blocked == other.blocked && budgetDuration == other.budgetDuration && budgetResetAt == other.budgetResetAt && config == other.config && createdAt == other.createdAt && createdBy == other.createdBy && endUserId == other.endUserId && endUserMaxBudget == other.endUserMaxBudget && endUserRpmLimit == other.endUserRpmLimit && endUserTpmLimit == other.endUserTpmLimit && expires == other.expires && keyAlias == other.keyAlias && keyName == other.keyName && lastRefreshedAt == other.lastRefreshedAt && llmBudgetTable == other.llmBudgetTable && maxBudget == other.maxBudget && maxParallelRequests == other.maxParallelRequests && metadata == other.metadata && modelMaxBudget == other.modelMaxBudget && modelSpend == other.modelSpend && models == other.models && orgId == other.orgId && parentOtelSpan == other.parentOtelSpan && permissions == other.permissions && rpmLimit == other.rpmLimit && rpmLimitPerModel == other.rpmLimitPerModel && softBudget == other.softBudget && softBudgetCooldown == other.softBudgetCooldown && spend == other.spend && teamAlias == other.teamAlias && teamBlocked == other.teamBlocked && teamId == other.teamId && teamMaxBudget == other.teamMaxBudget && teamMember == other.teamMember && teamMemberSpend == other.teamMemberSpend && teamMetadata == other.teamMetadata && teamModelAliases == other.teamModelAliases && teamModels == other.teamModels && teamRpmLimit == other.teamRpmLimit && teamSpend == other.teamSpend && teamTpmLimit == other.teamTpmLimit && tpmLimit == other.tpmLimit && tpmLimitPerModel == other.tpmLimitPerModel && updatedAt == other.updatedAt && updatedBy == other.updatedBy && userEmail == other.userEmail && userId == other.userId && userRole == other.userRole && userRpmLimit == other.userRpmLimit && userTpmLimit == other.userTpmLimit && additionalProperties == other.additionalProperties /* spotless:on */ + return other is LiteLlmDeletedVerificationToken && + id == other.id && + token == other.token && + aliases == other.aliases && + allowedCacheControls == other.allowedCacheControls && + allowedRoutes == other.allowedRoutes && + autoRotate == other.autoRotate && + blocked == other.blocked && + budgetDuration == other.budgetDuration && + budgetResetAt == other.budgetResetAt && + config == other.config && + createdAt == other.createdAt && + createdBy == other.createdBy && + deletedAt == other.deletedAt && + deletedBy == other.deletedBy && + deletedByApiKey == other.deletedByApiKey && + expires == other.expires && + keyAlias == other.keyAlias && + keyName == other.keyName && + keyRotationAt == other.keyRotationAt && + lastRotationAt == other.lastRotationAt && + litellmBudgetTable == other.litellmBudgetTable && + litellmChangedBy == other.litellmChangedBy && + maxBudget == other.maxBudget && + maxParallelRequests == other.maxParallelRequests && + metadata == other.metadata && + modelMaxBudget == other.modelMaxBudget && + modelSpend == other.modelSpend && + models == other.models && + objectPermission == other.objectPermission && + objectPermissionId == other.objectPermissionId && + orgId == other.orgId && + permissions == other.permissions && + rotationCount == other.rotationCount && + rotationInterval == other.rotationInterval && + routerSettings == other.routerSettings && + rpmLimit == other.rpmLimit && + softBudgetCooldown == other.softBudgetCooldown && + spend == other.spend && + teamId == other.teamId && + tpmLimit == other.tpmLimit && + updatedAt == other.updatedAt && + updatedBy == other.updatedBy && + userId == other.userId && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(token, aliases, allowedCacheControls, allowedModelRegion, apiKey, blocked, budgetDuration, budgetResetAt, config, createdAt, createdBy, endUserId, endUserMaxBudget, endUserRpmLimit, endUserTpmLimit, expires, keyAlias, keyName, lastRefreshedAt, llmBudgetTable, maxBudget, maxParallelRequests, metadata, modelMaxBudget, modelSpend, models, orgId, parentOtelSpan, permissions, rpmLimit, rpmLimitPerModel, softBudget, softBudgetCooldown, spend, teamAlias, teamBlocked, teamId, teamMaxBudget, teamMember, teamMemberSpend, teamMetadata, teamModelAliases, teamModels, teamRpmLimit, teamSpend, teamTpmLimit, tpmLimit, tpmLimitPerModel, updatedAt, updatedBy, userEmail, userId, userRole, userRpmLimit, userTpmLimit, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + id, + token, + aliases, + allowedCacheControls, + allowedRoutes, + autoRotate, + blocked, + budgetDuration, + budgetResetAt, + config, + createdAt, + createdBy, + deletedAt, + deletedBy, + deletedByApiKey, + expires, + keyAlias, + keyName, + keyRotationAt, + lastRotationAt, + litellmBudgetTable, + litellmChangedBy, + maxBudget, + maxParallelRequests, + metadata, + modelMaxBudget, + modelSpend, + models, + objectPermission, + objectPermissionId, + orgId, + permissions, + rotationCount, + rotationInterval, + routerSettings, + rpmLimit, + softBudgetCooldown, + spend, + teamId, + tpmLimit, + updatedAt, + updatedBy, + userId, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "UserApiKeyAuth{token=$token, aliases=$aliases, allowedCacheControls=$allowedCacheControls, allowedModelRegion=$allowedModelRegion, apiKey=$apiKey, blocked=$blocked, budgetDuration=$budgetDuration, budgetResetAt=$budgetResetAt, config=$config, createdAt=$createdAt, createdBy=$createdBy, endUserId=$endUserId, endUserMaxBudget=$endUserMaxBudget, endUserRpmLimit=$endUserRpmLimit, endUserTpmLimit=$endUserTpmLimit, expires=$expires, keyAlias=$keyAlias, keyName=$keyName, lastRefreshedAt=$lastRefreshedAt, llmBudgetTable=$llmBudgetTable, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelSpend=$modelSpend, models=$models, orgId=$orgId, parentOtelSpan=$parentOtelSpan, permissions=$permissions, rpmLimit=$rpmLimit, rpmLimitPerModel=$rpmLimitPerModel, softBudget=$softBudget, softBudgetCooldown=$softBudgetCooldown, spend=$spend, teamAlias=$teamAlias, teamBlocked=$teamBlocked, teamId=$teamId, teamMaxBudget=$teamMaxBudget, teamMember=$teamMember, teamMemberSpend=$teamMemberSpend, teamMetadata=$teamMetadata, teamModelAliases=$teamModelAliases, teamModels=$teamModels, teamRpmLimit=$teamRpmLimit, teamSpend=$teamSpend, teamTpmLimit=$teamTpmLimit, tpmLimit=$tpmLimit, tpmLimitPerModel=$tpmLimitPerModel, updatedAt=$updatedAt, updatedBy=$updatedBy, userEmail=$userEmail, userId=$userId, userRole=$userRole, userRpmLimit=$userRpmLimit, userTpmLimit=$userTpmLimit, additionalProperties=$additionalProperties}" + "LiteLlmDeletedVerificationToken{id=$id, token=$token, aliases=$aliases, allowedCacheControls=$allowedCacheControls, allowedRoutes=$allowedRoutes, autoRotate=$autoRotate, blocked=$blocked, budgetDuration=$budgetDuration, budgetResetAt=$budgetResetAt, config=$config, createdAt=$createdAt, createdBy=$createdBy, deletedAt=$deletedAt, deletedBy=$deletedBy, deletedByApiKey=$deletedByApiKey, expires=$expires, keyAlias=$keyAlias, keyName=$keyName, keyRotationAt=$keyRotationAt, lastRotationAt=$lastRotationAt, litellmBudgetTable=$litellmBudgetTable, litellmChangedBy=$litellmChangedBy, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelSpend=$modelSpend, models=$models, objectPermission=$objectPermission, objectPermissionId=$objectPermissionId, orgId=$orgId, permissions=$permissions, rotationCount=$rotationCount, rotationInterval=$rotationInterval, routerSettings=$routerSettings, rpmLimit=$rpmLimit, softBudgetCooldown=$softBudgetCooldown, spend=$spend, teamId=$teamId, tpmLimit=$tpmLimit, updatedAt=$updatedAt, updatedBy=$updatedBy, userId=$userId, additionalProperties=$additionalProperties}" } } @@ -3264,12 +10353,17 @@ private constructor( return true } - return /* spotless:off */ other is KeyListResponse && currentPage == other.currentPage && keys == other.keys && totalCount == other.totalCount && totalPages == other.totalPages && additionalProperties == other.additionalProperties /* spotless:on */ + return other is KeyListResponse && + currentPage == other.currentPage && + keys == other.keys && + totalCount == other.totalCount && + totalPages == other.totalPages && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(currentPage, keys, totalCount, totalPages, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash(currentPage, keys, totalCount, totalPages, additionalProperties) + } override fun hashCode(): Int = hashCode diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRegenerateByKeyParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRegenerateByKeyParams.kt index ec7044cd..6f4ffd66 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRegenerateByKeyParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRegenerateByKeyParams.kt @@ -4,7 +4,6 @@ package ai.hanzo.api.models.key import ai.hanzo.api.core.JsonValue import ai.hanzo.api.core.Params -import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.http.Headers import ai.hanzo.api.core.http.QueryParams import ai.hanzo.api.core.immutableEmptyMap @@ -19,6 +18,10 @@ import kotlin.jvm.optionals.getOrNull * Parameters: * - key: str (path parameter) - The key to regenerate * - data: Optional[RegenerateKeyRequest] - Request body containing optional parameters to update + * - key: Optional[str] - The key to regenerate. + * - new_master_key: Optional[str] - The new master key to use, if key is the master key. + * - new_key: Optional[str] - The new key to use, if key is not the master key. If both set, + * new_master_key will be used. * - key_alias: Optional[str] - User-friendly key alias * - user_id: Optional[str] - User ID associated with key * - team_id: Optional[str] - Team ID associated with key @@ -61,20 +64,20 @@ import kotlin.jvm.optionals.getOrNull */ class KeyRegenerateByKeyParams private constructor( - private val pathKey: String, - private val llmChangedBy: String?, + private val pathKey: String?, + private val litellmChangedBy: String?, private val regenerateKeyRequest: RegenerateKeyRequest?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { - fun pathKey(): String = pathKey + fun pathKey(): Optional = Optional.ofNullable(pathKey) /** - * The llm-changed-by header enables tracking of actions performed by authorized users on behalf - * of other users, providing an audit trail for accountability + * The litellm-changed-by header enables tracking of actions performed by authorized users on + * behalf of other users, providing an audit trail for accountability */ - fun llmChangedBy(): Optional = Optional.ofNullable(llmChangedBy) + fun litellmChangedBy(): Optional = Optional.ofNullable(litellmChangedBy) fun regenerateKeyRequest(): Optional = Optional.ofNullable(regenerateKeyRequest) @@ -82,22 +85,19 @@ private constructor( fun _additionalBodyProperties(): Map = regenerateKeyRequest?._additionalProperties() ?: immutableEmptyMap() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [KeyRegenerateByKeyParams]. - * - * The following fields are required: - * ```java - * .pathKey() - * ``` - */ + @JvmStatic fun none(): KeyRegenerateByKeyParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [KeyRegenerateByKeyParams]. */ @JvmStatic fun builder() = Builder() } @@ -105,7 +105,7 @@ private constructor( class Builder internal constructor() { private var pathKey: String? = null - private var llmChangedBy: String? = null + private var litellmChangedBy: String? = null private var regenerateKeyRequest: RegenerateKeyRequest? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @@ -113,22 +113,28 @@ private constructor( @JvmSynthetic internal fun from(keyRegenerateByKeyParams: KeyRegenerateByKeyParams) = apply { pathKey = keyRegenerateByKeyParams.pathKey - llmChangedBy = keyRegenerateByKeyParams.llmChangedBy + litellmChangedBy = keyRegenerateByKeyParams.litellmChangedBy regenerateKeyRequest = keyRegenerateByKeyParams.regenerateKeyRequest additionalHeaders = keyRegenerateByKeyParams.additionalHeaders.toBuilder() additionalQueryParams = keyRegenerateByKeyParams.additionalQueryParams.toBuilder() } - fun pathKey(pathKey: String) = apply { this.pathKey = pathKey } + fun pathKey(pathKey: String?) = apply { this.pathKey = pathKey } + + /** Alias for calling [Builder.pathKey] with `pathKey.orElse(null)`. */ + fun pathKey(pathKey: Optional) = pathKey(pathKey.getOrNull()) /** - * The llm-changed-by header enables tracking of actions performed by authorized users on - * behalf of other users, providing an audit trail for accountability + * The litellm-changed-by header enables tracking of actions performed by authorized users + * on behalf of other users, providing an audit trail for accountability */ - fun llmChangedBy(llmChangedBy: String?) = apply { this.llmChangedBy = llmChangedBy } + fun litellmChangedBy(litellmChangedBy: String?) = apply { + this.litellmChangedBy = litellmChangedBy + } - /** Alias for calling [Builder.llmChangedBy] with `llmChangedBy.orElse(null)`. */ - fun llmChangedBy(llmChangedBy: Optional) = llmChangedBy(llmChangedBy.getOrNull()) + /** Alias for calling [Builder.litellmChangedBy] with `litellmChangedBy.orElse(null)`. */ + fun litellmChangedBy(litellmChangedBy: Optional) = + litellmChangedBy(litellmChangedBy.getOrNull()) fun regenerateKeyRequest(regenerateKeyRequest: RegenerateKeyRequest?) = apply { this.regenerateKeyRequest = regenerateKeyRequest @@ -243,37 +249,29 @@ private constructor( * Returns an immutable instance of [KeyRegenerateByKeyParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .pathKey() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): KeyRegenerateByKeyParams = KeyRegenerateByKeyParams( - checkRequired("pathKey", pathKey), - llmChangedBy, + pathKey, + litellmChangedBy, regenerateKeyRequest, additionalHeaders.build(), additionalQueryParams.build(), ) } - @JvmSynthetic - internal fun _body(): Optional = Optional.ofNullable(regenerateKeyRequest) + fun _body(): Optional = Optional.ofNullable(regenerateKeyRequest) fun _pathParam(index: Int): String = when (index) { - 0 -> pathKey + 0 -> pathKey ?: "" else -> "" } override fun _headers(): Headers = Headers.builder() .apply { - llmChangedBy?.let { put("llm-changed-by", it) } + litellmChangedBy?.let { put("litellm-changed-by", it) } putAll(additionalHeaders) } .build() @@ -285,11 +283,23 @@ private constructor( return true } - return /* spotless:off */ other is KeyRegenerateByKeyParams && pathKey == other.pathKey && llmChangedBy == other.llmChangedBy && regenerateKeyRequest == other.regenerateKeyRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is KeyRegenerateByKeyParams && + pathKey == other.pathKey && + litellmChangedBy == other.litellmChangedBy && + regenerateKeyRequest == other.regenerateKeyRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(pathKey, llmChangedBy, regenerateKeyRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + pathKey, + litellmChangedBy, + regenerateKeyRequest, + additionalHeaders, + additionalQueryParams, + ) override fun toString() = - "KeyRegenerateByKeyParams{pathKey=$pathKey, llmChangedBy=$llmChangedBy, regenerateKeyRequest=$regenerateKeyRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "KeyRegenerateByKeyParams{pathKey=$pathKey, litellmChangedBy=$litellmChangedBy, regenerateKeyRequest=$regenerateKeyRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRetrieveInfoParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRetrieveInfoParams.kt index 2705dab2..abc8ce75 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRetrieveInfoParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRetrieveInfoParams.kt @@ -16,13 +16,13 @@ import kotlin.jvm.optionals.getOrNull * * Example Curl: * ``` - * curl -X GET "http://0.0.0.0:4000/key/info?key=sk-02Wr4IAlN3NvPXvL5JVvDA" -H "Authorization: Bearer sk-1234" + * curl -X GET "http://0.0.0.0:4000/key/info?key=sk-test-example-key-123" -H "Authorization: Bearer sk-1234" * ``` * * Example Curl - if no key is passed, it will use the Key Passed in Authorization Header * * ``` - * curl -X GET "http://0.0.0.0:4000/key/info" -H "Authorization: Bearer sk-02Wr4IAlN3NvPXvL5JVvDA" + * curl -X GET "http://0.0.0.0:4000/key/info" -H "Authorization: Bearer sk-test-example-key-123" * ``` */ class KeyRetrieveInfoParams @@ -35,8 +35,10 @@ private constructor( /** Key in the request parameters */ fun key(): Optional = Optional.ofNullable(key) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -191,10 +193,13 @@ private constructor( return true } - return /* spotless:off */ other is KeyRetrieveInfoParams && key == other.key && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is KeyRetrieveInfoParams && + key == other.key && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(key, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(key, additionalHeaders, additionalQueryParams) override fun toString() = "KeyRetrieveInfoParams{key=$key, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRetrieveInfoResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRetrieveInfoResponse.kt index 5f2f1511..3550ba6e 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRetrieveInfoResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyRetrieveInfoResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.key import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class KeyRetrieveInfoResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(llmChangedBy) + fun litellmChangedBy(): Optional = Optional.ofNullable(litellmChangedBy) fun blockKeyRequest(): BlockKeyRequest = blockKeyRequest fun _additionalBodyProperties(): Map = blockKeyRequest._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -67,27 +69,30 @@ private constructor( /** A builder for [KeyUnblockParams]. */ class Builder internal constructor() { - private var llmChangedBy: String? = null + private var litellmChangedBy: String? = null private var blockKeyRequest: BlockKeyRequest? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(keyUnblockParams: KeyUnblockParams) = apply { - llmChangedBy = keyUnblockParams.llmChangedBy + litellmChangedBy = keyUnblockParams.litellmChangedBy blockKeyRequest = keyUnblockParams.blockKeyRequest additionalHeaders = keyUnblockParams.additionalHeaders.toBuilder() additionalQueryParams = keyUnblockParams.additionalQueryParams.toBuilder() } /** - * The llm-changed-by header enables tracking of actions performed by authorized users on - * behalf of other users, providing an audit trail for accountability + * The litellm-changed-by header enables tracking of actions performed by authorized users + * on behalf of other users, providing an audit trail for accountability */ - fun llmChangedBy(llmChangedBy: String?) = apply { this.llmChangedBy = llmChangedBy } + fun litellmChangedBy(litellmChangedBy: String?) = apply { + this.litellmChangedBy = litellmChangedBy + } - /** Alias for calling [Builder.llmChangedBy] with `llmChangedBy.orElse(null)`. */ - fun llmChangedBy(llmChangedBy: Optional) = llmChangedBy(llmChangedBy.getOrNull()) + /** Alias for calling [Builder.litellmChangedBy] with `litellmChangedBy.orElse(null)`. */ + fun litellmChangedBy(litellmChangedBy: Optional) = + litellmChangedBy(litellmChangedBy.getOrNull()) fun blockKeyRequest(blockKeyRequest: BlockKeyRequest) = apply { this.blockKeyRequest = blockKeyRequest @@ -205,19 +210,19 @@ private constructor( */ fun build(): KeyUnblockParams = KeyUnblockParams( - llmChangedBy, + litellmChangedBy, checkRequired("blockKeyRequest", blockKeyRequest), additionalHeaders.build(), additionalQueryParams.build(), ) } - @JvmSynthetic internal fun _body(): BlockKeyRequest = blockKeyRequest + fun _body(): BlockKeyRequest = blockKeyRequest override fun _headers(): Headers = Headers.builder() .apply { - llmChangedBy?.let { put("llm-changed-by", it) } + litellmChangedBy?.let { put("litellm-changed-by", it) } putAll(additionalHeaders) } .build() @@ -229,11 +234,16 @@ private constructor( return true } - return /* spotless:off */ other is KeyUnblockParams && llmChangedBy == other.llmChangedBy && blockKeyRequest == other.blockKeyRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is KeyUnblockParams && + litellmChangedBy == other.litellmChangedBy && + blockKeyRequest == other.blockKeyRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(llmChangedBy, blockKeyRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(litellmChangedBy, blockKeyRequest, additionalHeaders, additionalQueryParams) override fun toString() = - "KeyUnblockParams{llmChangedBy=$llmChangedBy, blockKeyRequest=$blockKeyRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "KeyUnblockParams{litellmChangedBy=$litellmChangedBy, blockKeyRequest=$blockKeyRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyUnblockResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyUnblockResponse.kt index a424a0ad..97bba5b7 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyUnblockResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyUnblockResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.key import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class KeyUnblockResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(llmChangedBy) + fun litellmChangedBy(): Optional = Optional.ofNullable(litellmChangedBy) /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly @@ -97,7 +128,11 @@ private constructor( */ fun key(): String = body.key() - fun _aliases(): JsonValue = body._aliases() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aliases(): Optional = body.aliases() /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -105,6 +140,31 @@ private constructor( */ fun allowedCacheControls(): Optional> = body.allowedCacheControls() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedPassthroughRoutes(): Optional> = body.allowedPassthroughRoutes() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedRoutes(): Optional> = body.allowedRoutes() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedVectorStoreIndexes(): Optional> = + body.allowedVectorStoreIndexes() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun autoRotate(): Optional = body.autoRotate() + /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). @@ -123,7 +183,11 @@ private constructor( */ fun budgetId(): Optional = body.budgetId() - fun _config(): JsonValue = body._config() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun config(): Optional = body.config() /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -161,13 +225,29 @@ private constructor( */ fun maxParallelRequests(): Optional = body.maxParallelRequests() - fun _metadata(): JsonValue = body._metadata() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = body.metadata() - fun _modelMaxBudget(): JsonValue = body._modelMaxBudget() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelMaxBudget(): Optional = body.modelMaxBudget() - fun _modelRpmLimit(): JsonValue = body._modelRpmLimit() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelRpmLimit(): Optional = body.modelRpmLimit() - fun _modelTpmLimit(): JsonValue = body._modelTpmLimit() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelTpmLimit(): Optional = body.modelTpmLimit() /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -175,7 +255,37 @@ private constructor( */ fun models(): Optional> = body.models() - fun _permissions(): JsonValue = body._permissions() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun objectPermission(): Optional = body.objectPermission() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun permissions(): Optional = body.permissions() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun prompts(): Optional> = body.prompts() + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rotationInterval(): Optional = body.rotationInterval() + + /** + * Set of params that you can modify via `router.update_settings()`. + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routerSettings(): Optional = body.routerSettings() /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -183,6 +293,12 @@ private constructor( */ fun rpmLimit(): Optional = body.rpmLimit() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rpmLimitType(): Optional = body.rpmLimitType() + /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). @@ -219,6 +335,12 @@ private constructor( */ fun tpmLimit(): Optional = body.tpmLimit() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tpmLimitType(): Optional = body.tpmLimitType() + /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). @@ -232,6 +354,13 @@ private constructor( */ fun _key(): JsonField = body._key() + /** + * Returns the raw JSON value of [aliases]. + * + * Unlike [aliases], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _aliases(): JsonField = body._aliases() + /** * Returns the raw JSON value of [allowedCacheControls]. * @@ -240,6 +369,37 @@ private constructor( */ fun _allowedCacheControls(): JsonField> = body._allowedCacheControls() + /** + * Returns the raw JSON value of [allowedPassthroughRoutes]. + * + * Unlike [allowedPassthroughRoutes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + fun _allowedPassthroughRoutes(): JsonField> = body._allowedPassthroughRoutes() + + /** + * Returns the raw JSON value of [allowedRoutes]. + * + * Unlike [allowedRoutes], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _allowedRoutes(): JsonField> = body._allowedRoutes() + + /** + * Returns the raw JSON value of [allowedVectorStoreIndexes]. + * + * Unlike [allowedVectorStoreIndexes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + fun _allowedVectorStoreIndexes(): JsonField> = + body._allowedVectorStoreIndexes() + + /** + * Returns the raw JSON value of [autoRotate]. + * + * Unlike [autoRotate], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _autoRotate(): JsonField = body._autoRotate() + /** * Returns the raw JSON value of [blocked]. * @@ -261,6 +421,13 @@ private constructor( */ fun _budgetId(): JsonField = body._budgetId() + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _config(): JsonField = body._config() + /** * Returns the raw JSON value of [duration]. * @@ -304,6 +471,34 @@ private constructor( */ fun _maxParallelRequests(): JsonField = body._maxParallelRequests() + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [modelMaxBudget]. + * + * Unlike [modelMaxBudget], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _modelMaxBudget(): JsonField = body._modelMaxBudget() + + /** + * Returns the raw JSON value of [modelRpmLimit]. + * + * Unlike [modelRpmLimit], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _modelRpmLimit(): JsonField = body._modelRpmLimit() + + /** + * Returns the raw JSON value of [modelTpmLimit]. + * + * Unlike [modelTpmLimit], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _modelTpmLimit(): JsonField = body._modelTpmLimit() + /** * Returns the raw JSON value of [models]. * @@ -311,6 +506,43 @@ private constructor( */ fun _models(): JsonField> = body._models() + /** + * Returns the raw JSON value of [objectPermission]. + * + * Unlike [objectPermission], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _objectPermission(): JsonField = body._objectPermission() + + /** + * Returns the raw JSON value of [permissions]. + * + * Unlike [permissions], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _permissions(): JsonField = body._permissions() + + /** + * Returns the raw JSON value of [prompts]. + * + * Unlike [prompts], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _prompts(): JsonField> = body._prompts() + + /** + * Returns the raw JSON value of [rotationInterval]. + * + * Unlike [rotationInterval], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _rotationInterval(): JsonField = body._rotationInterval() + + /** + * Returns the raw JSON value of [routerSettings]. + * + * Unlike [routerSettings], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _routerSettings(): JsonField = body._routerSettings() + /** * Returns the raw JSON value of [rpmLimit]. * @@ -318,6 +550,13 @@ private constructor( */ fun _rpmLimit(): JsonField = body._rpmLimit() + /** + * Returns the raw JSON value of [rpmLimitType]. + * + * Unlike [rpmLimitType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _rpmLimitType(): JsonField = body._rpmLimitType() + /** * Returns the raw JSON value of [spend]. * @@ -362,6 +601,13 @@ private constructor( */ fun _tpmLimit(): JsonField = body._tpmLimit() + /** + * Returns the raw JSON value of [tpmLimitType]. + * + * Unlike [tpmLimitType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tpmLimitType(): JsonField = body._tpmLimitType() + /** * Returns the raw JSON value of [userId]. * @@ -371,8 +617,10 @@ private constructor( fun _additionalBodyProperties(): Map = body._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -393,27 +641,44 @@ private constructor( /** A builder for [KeyUpdateParams]. */ class Builder internal constructor() { - private var llmChangedBy: String? = null + private var litellmChangedBy: String? = null private var body: Body.Builder = Body.builder() private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(keyUpdateParams: KeyUpdateParams) = apply { - llmChangedBy = keyUpdateParams.llmChangedBy + litellmChangedBy = keyUpdateParams.litellmChangedBy body = keyUpdateParams.body.toBuilder() additionalHeaders = keyUpdateParams.additionalHeaders.toBuilder() additionalQueryParams = keyUpdateParams.additionalQueryParams.toBuilder() } /** - * The llm-changed-by header enables tracking of actions performed by authorized users on - * behalf of other users, providing an audit trail for accountability + * The litellm-changed-by header enables tracking of actions performed by authorized users + * on behalf of other users, providing an audit trail for accountability */ - fun llmChangedBy(llmChangedBy: String?) = apply { this.llmChangedBy = llmChangedBy } + fun litellmChangedBy(litellmChangedBy: String?) = apply { + this.litellmChangedBy = litellmChangedBy + } - /** Alias for calling [Builder.llmChangedBy] with `llmChangedBy.orElse(null)`. */ - fun llmChangedBy(llmChangedBy: Optional) = llmChangedBy(llmChangedBy.getOrNull()) + /** Alias for calling [Builder.litellmChangedBy] with `litellmChangedBy.orElse(null)`. */ + fun litellmChangedBy(litellmChangedBy: Optional) = + litellmChangedBy(litellmChangedBy.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [key] + * - [aliases] + * - [allowedCacheControls] + * - [allowedPassthroughRoutes] + * - [allowedRoutes] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } fun key(key: String) = apply { body.key(key) } @@ -425,7 +690,18 @@ private constructor( */ fun key(key: JsonField) = apply { body.key(key) } - fun aliases(aliases: JsonValue) = apply { body.aliases(aliases) } + fun aliases(aliases: Aliases?) = apply { body.aliases(aliases) } + + /** Alias for calling [Builder.aliases] with `aliases.orElse(null)`. */ + fun aliases(aliases: Optional) = aliases(aliases.getOrNull()) + + /** + * Sets [Builder.aliases] to an arbitrary JSON value. + * + * You should usually call [Builder.aliases] with a well-typed [Aliases] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun aliases(aliases: JsonField) = apply { body.aliases(aliases) } fun allowedCacheControls(allowedCacheControls: List?) = apply { body.allowedCacheControls(allowedCacheControls) @@ -458,6 +734,117 @@ private constructor( body.addAllowedCacheControl(allowedCacheControl) } + fun allowedPassthroughRoutes(allowedPassthroughRoutes: List?) = apply { + body.allowedPassthroughRoutes(allowedPassthroughRoutes) + } + + /** + * Alias for calling [Builder.allowedPassthroughRoutes] with + * `allowedPassthroughRoutes.orElse(null)`. + */ + fun allowedPassthroughRoutes(allowedPassthroughRoutes: Optional>) = + allowedPassthroughRoutes(allowedPassthroughRoutes.getOrNull()) + + /** + * Sets [Builder.allowedPassthroughRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedPassthroughRoutes] with a well-typed + * `List` value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun allowedPassthroughRoutes(allowedPassthroughRoutes: JsonField>) = apply { + body.allowedPassthroughRoutes(allowedPassthroughRoutes) + } + + /** + * Adds a single [JsonValue] to [allowedPassthroughRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedPassthroughRoute(allowedPassthroughRoute: JsonValue) = apply { + body.addAllowedPassthroughRoute(allowedPassthroughRoute) + } + + fun allowedRoutes(allowedRoutes: List?) = apply { + body.allowedRoutes(allowedRoutes) + } + + /** Alias for calling [Builder.allowedRoutes] with `allowedRoutes.orElse(null)`. */ + fun allowedRoutes(allowedRoutes: Optional>) = + allowedRoutes(allowedRoutes.getOrNull()) + + /** + * Sets [Builder.allowedRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedRoutes] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun allowedRoutes(allowedRoutes: JsonField>) = apply { + body.allowedRoutes(allowedRoutes) + } + + /** + * Adds a single [JsonValue] to [allowedRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedRoute(allowedRoute: JsonValue) = apply { body.addAllowedRoute(allowedRoute) } + + fun allowedVectorStoreIndexes(allowedVectorStoreIndexes: List?) = + apply { + body.allowedVectorStoreIndexes(allowedVectorStoreIndexes) + } + + /** + * Alias for calling [Builder.allowedVectorStoreIndexes] with + * `allowedVectorStoreIndexes.orElse(null)`. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: Optional> + ) = allowedVectorStoreIndexes(allowedVectorStoreIndexes.getOrNull()) + + /** + * Sets [Builder.allowedVectorStoreIndexes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedVectorStoreIndexes] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: JsonField> + ) = apply { body.allowedVectorStoreIndexes(allowedVectorStoreIndexes) } + + /** + * Adds a single [AllowedVectorStoreIndex] to [allowedVectorStoreIndexes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedVectorStoreIndex(allowedVectorStoreIndex: AllowedVectorStoreIndex) = apply { + body.addAllowedVectorStoreIndex(allowedVectorStoreIndex) + } + + fun autoRotate(autoRotate: Boolean?) = apply { body.autoRotate(autoRotate) } + + /** + * Alias for [Builder.autoRotate]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun autoRotate(autoRotate: Boolean) = autoRotate(autoRotate as Boolean?) + + /** Alias for calling [Builder.autoRotate] with `autoRotate.orElse(null)`. */ + fun autoRotate(autoRotate: Optional) = autoRotate(autoRotate.getOrNull()) + + /** + * Sets [Builder.autoRotate] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRotate] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun autoRotate(autoRotate: JsonField) = apply { body.autoRotate(autoRotate) } + fun blocked(blocked: Boolean?) = apply { body.blocked(blocked) } /** @@ -508,7 +895,18 @@ private constructor( */ fun budgetId(budgetId: JsonField) = apply { body.budgetId(budgetId) } - fun config(config: JsonValue) = apply { body.config(config) } + fun config(config: Config?) = apply { body.config(config) } + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [Config] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun config(config: JsonField) = apply { body.config(config) } fun duration(duration: String?) = apply { body.duration(duration) } @@ -633,38 +1031,192 @@ private constructor( body.maxParallelRequests(maxParallelRequests) } - fun metadata(metadata: JsonValue) = apply { body.metadata(metadata) } + fun metadata(metadata: Metadata?) = apply { body.metadata(metadata) } - fun modelMaxBudget(modelMaxBudget: JsonValue) = apply { - body.modelMaxBudget(modelMaxBudget) - } + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) - fun modelRpmLimit(modelRpmLimit: JsonValue) = apply { body.modelRpmLimit(modelRpmLimit) } - - fun modelTpmLimit(modelTpmLimit: JsonValue) = apply { body.modelTpmLimit(modelTpmLimit) } + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun metadata(metadata: JsonField) = apply { body.metadata(metadata) } - fun models(models: List?) = apply { body.models(models) } + fun modelMaxBudget(modelMaxBudget: ModelMaxBudget?) = apply { + body.modelMaxBudget(modelMaxBudget) + } - /** Alias for calling [Builder.models] with `models.orElse(null)`. */ - fun models(models: Optional>) = models(models.getOrNull()) + /** Alias for calling [Builder.modelMaxBudget] with `modelMaxBudget.orElse(null)`. */ + fun modelMaxBudget(modelMaxBudget: Optional) = + modelMaxBudget(modelMaxBudget.getOrNull()) /** - * Sets [Builder.models] to an arbitrary JSON value. + * Sets [Builder.modelMaxBudget] to an arbitrary JSON value. * - * You should usually call [Builder.models] with a well-typed `List` value + * You should usually call [Builder.modelMaxBudget] with a well-typed [ModelMaxBudget] value * instead. This method is primarily for setting the field to an undocumented or not yet * supported value. */ - fun models(models: JsonField>) = apply { body.models(models) } + fun modelMaxBudget(modelMaxBudget: JsonField) = apply { + body.modelMaxBudget(modelMaxBudget) + } + + fun modelRpmLimit(modelRpmLimit: ModelRpmLimit?) = apply { + body.modelRpmLimit(modelRpmLimit) + } + + /** Alias for calling [Builder.modelRpmLimit] with `modelRpmLimit.orElse(null)`. */ + fun modelRpmLimit(modelRpmLimit: Optional) = + modelRpmLimit(modelRpmLimit.getOrNull()) /** - * Adds a single [JsonValue] to [models]. + * Sets [Builder.modelRpmLimit] to an arbitrary JSON value. * - * @throws IllegalStateException if the field was previously set to a non-list. + * You should usually call [Builder.modelRpmLimit] with a well-typed [ModelRpmLimit] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun addModel(model: JsonValue) = apply { body.addModel(model) } + fun modelRpmLimit(modelRpmLimit: JsonField) = apply { + body.modelRpmLimit(modelRpmLimit) + } - fun permissions(permissions: JsonValue) = apply { body.permissions(permissions) } + fun modelTpmLimit(modelTpmLimit: ModelTpmLimit?) = apply { + body.modelTpmLimit(modelTpmLimit) + } + + /** Alias for calling [Builder.modelTpmLimit] with `modelTpmLimit.orElse(null)`. */ + fun modelTpmLimit(modelTpmLimit: Optional) = + modelTpmLimit(modelTpmLimit.getOrNull()) + + /** + * Sets [Builder.modelTpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.modelTpmLimit] with a well-typed [ModelTpmLimit] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelTpmLimit(modelTpmLimit: JsonField) = apply { + body.modelTpmLimit(modelTpmLimit) + } + + fun models(models: List?) = apply { body.models(models) } + + /** Alias for calling [Builder.models] with `models.orElse(null)`. */ + fun models(models: Optional>) = models(models.getOrNull()) + + /** + * Sets [Builder.models] to an arbitrary JSON value. + * + * You should usually call [Builder.models] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun models(models: JsonField>) = apply { body.models(models) } + + /** + * Adds a single [JsonValue] to [models]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addModel(model: JsonValue) = apply { body.addModel(model) } + + fun objectPermission(objectPermission: ObjectPermission?) = apply { + body.objectPermission(objectPermission) + } + + /** Alias for calling [Builder.objectPermission] with `objectPermission.orElse(null)`. */ + fun objectPermission(objectPermission: Optional) = + objectPermission(objectPermission.getOrNull()) + + /** + * Sets [Builder.objectPermission] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermission] with a well-typed [ObjectPermission] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun objectPermission(objectPermission: JsonField) = apply { + body.objectPermission(objectPermission) + } + + fun permissions(permissions: Permissions?) = apply { body.permissions(permissions) } + + /** Alias for calling [Builder.permissions] with `permissions.orElse(null)`. */ + fun permissions(permissions: Optional) = permissions(permissions.getOrNull()) + + /** + * Sets [Builder.permissions] to an arbitrary JSON value. + * + * You should usually call [Builder.permissions] with a well-typed [Permissions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun permissions(permissions: JsonField) = apply { + body.permissions(permissions) + } + + fun prompts(prompts: List?) = apply { body.prompts(prompts) } + + /** Alias for calling [Builder.prompts] with `prompts.orElse(null)`. */ + fun prompts(prompts: Optional>) = prompts(prompts.getOrNull()) + + /** + * Sets [Builder.prompts] to an arbitrary JSON value. + * + * You should usually call [Builder.prompts] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun prompts(prompts: JsonField>) = apply { body.prompts(prompts) } + + /** + * Adds a single [String] to [prompts]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addPrompt(prompt: String) = apply { body.addPrompt(prompt) } + + fun rotationInterval(rotationInterval: String?) = apply { + body.rotationInterval(rotationInterval) + } + + /** Alias for calling [Builder.rotationInterval] with `rotationInterval.orElse(null)`. */ + fun rotationInterval(rotationInterval: Optional) = + rotationInterval(rotationInterval.getOrNull()) + + /** + * Sets [Builder.rotationInterval] to an arbitrary JSON value. + * + * You should usually call [Builder.rotationInterval] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rotationInterval(rotationInterval: JsonField) = apply { + body.rotationInterval(rotationInterval) + } + + /** Set of params that you can modify via `router.update_settings()`. */ + fun routerSettings(routerSettings: RouterSettings?) = apply { + body.routerSettings(routerSettings) + } + + /** Alias for calling [Builder.routerSettings] with `routerSettings.orElse(null)`. */ + fun routerSettings(routerSettings: Optional) = + routerSettings(routerSettings.getOrNull()) + + /** + * Sets [Builder.routerSettings] to an arbitrary JSON value. + * + * You should usually call [Builder.routerSettings] with a well-typed [RouterSettings] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun routerSettings(routerSettings: JsonField) = apply { + body.routerSettings(routerSettings) + } fun rpmLimit(rpmLimit: Long?) = apply { body.rpmLimit(rpmLimit) } @@ -686,6 +1238,23 @@ private constructor( */ fun rpmLimit(rpmLimit: JsonField) = apply { body.rpmLimit(rpmLimit) } + fun rpmLimitType(rpmLimitType: RpmLimitType?) = apply { body.rpmLimitType(rpmLimitType) } + + /** Alias for calling [Builder.rpmLimitType] with `rpmLimitType.orElse(null)`. */ + fun rpmLimitType(rpmLimitType: Optional) = + rpmLimitType(rpmLimitType.getOrNull()) + + /** + * Sets [Builder.rpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.rpmLimitType] with a well-typed [RpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rpmLimitType(rpmLimitType: JsonField) = apply { + body.rpmLimitType(rpmLimitType) + } + fun spend(spend: Double?) = apply { body.spend(spend) } /** @@ -808,6 +1377,23 @@ private constructor( */ fun tpmLimit(tpmLimit: JsonField) = apply { body.tpmLimit(tpmLimit) } + fun tpmLimitType(tpmLimitType: TpmLimitType?) = apply { body.tpmLimitType(tpmLimitType) } + + /** Alias for calling [Builder.tpmLimitType] with `tpmLimitType.orElse(null)`. */ + fun tpmLimitType(tpmLimitType: Optional) = + tpmLimitType(tpmLimitType.getOrNull()) + + /** + * Sets [Builder.tpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.tpmLimitType] with a well-typed [TpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tpmLimitType(tpmLimitType: JsonField) = apply { + body.tpmLimitType(tpmLimitType) + } + fun userId(userId: String?) = apply { body.userId(userId) } /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ @@ -952,19 +1538,19 @@ private constructor( */ fun build(): KeyUpdateParams = KeyUpdateParams( - llmChangedBy, + litellmChangedBy, body.build(), additionalHeaders.build(), additionalQueryParams.build(), ) } - @JvmSynthetic internal fun _body(): Body = body + fun _body(): Body = body override fun _headers(): Headers = Headers.builder() .apply { - llmChangedBy?.let { put("llm-changed-by", it) } + litellmChangedBy?.let { put("litellm-changed-by", it) } putAll(additionalHeaders) } .build() @@ -972,33 +1558,44 @@ private constructor( override fun _queryParams(): QueryParams = additionalQueryParams class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val key: JsonField, - private val aliases: JsonValue, + private val aliases: JsonField, private val allowedCacheControls: JsonField>, + private val allowedPassthroughRoutes: JsonField>, + private val allowedRoutes: JsonField>, + private val allowedVectorStoreIndexes: JsonField>, + private val autoRotate: JsonField, private val blocked: JsonField, private val budgetDuration: JsonField, private val budgetId: JsonField, - private val config: JsonValue, + private val config: JsonField, private val duration: JsonField, private val enforcedParams: JsonField>, private val guardrails: JsonField>, private val keyAlias: JsonField, private val maxBudget: JsonField, private val maxParallelRequests: JsonField, - private val metadata: JsonValue, - private val modelMaxBudget: JsonValue, - private val modelRpmLimit: JsonValue, - private val modelTpmLimit: JsonValue, + private val metadata: JsonField, + private val modelMaxBudget: JsonField, + private val modelRpmLimit: JsonField, + private val modelTpmLimit: JsonField, private val models: JsonField>, - private val permissions: JsonValue, + private val objectPermission: JsonField, + private val permissions: JsonField, + private val prompts: JsonField>, + private val rotationInterval: JsonField, + private val routerSettings: JsonField, private val rpmLimit: JsonField, + private val rpmLimitType: JsonField, private val spend: JsonField, private val tags: JsonField>, private val teamId: JsonField, private val tempBudgetExpiry: JsonField, private val tempBudgetIncrease: JsonField, private val tpmLimit: JsonField, + private val tpmLimitType: JsonField, private val userId: JsonField, private val additionalProperties: MutableMap, ) { @@ -1006,10 +1603,22 @@ private constructor( @JsonCreator private constructor( @JsonProperty("key") @ExcludeMissing key: JsonField = JsonMissing.of(), - @JsonProperty("aliases") @ExcludeMissing aliases: JsonValue = JsonMissing.of(), + @JsonProperty("aliases") @ExcludeMissing aliases: JsonField = JsonMissing.of(), @JsonProperty("allowed_cache_controls") @ExcludeMissing allowedCacheControls: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_passthrough_routes") + @ExcludeMissing + allowedPassthroughRoutes: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_routes") + @ExcludeMissing + allowedRoutes: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_vector_store_indexes") + @ExcludeMissing + allowedVectorStoreIndexes: JsonField> = JsonMissing.of(), + @JsonProperty("auto_rotate") + @ExcludeMissing + autoRotate: JsonField = JsonMissing.of(), @JsonProperty("blocked") @ExcludeMissing blocked: JsonField = JsonMissing.of(), @JsonProperty("budget_duration") @ExcludeMissing @@ -1017,7 +1626,7 @@ private constructor( @JsonProperty("budget_id") @ExcludeMissing budgetId: JsonField = JsonMissing.of(), - @JsonProperty("config") @ExcludeMissing config: JsonValue = JsonMissing.of(), + @JsonProperty("config") @ExcludeMissing config: JsonField = JsonMissing.of(), @JsonProperty("duration") @ExcludeMissing duration: JsonField = JsonMissing.of(), @@ -1036,21 +1645,40 @@ private constructor( @JsonProperty("max_parallel_requests") @ExcludeMissing maxParallelRequests: JsonField = JsonMissing.of(), - @JsonProperty("metadata") @ExcludeMissing metadata: JsonValue = JsonMissing.of(), + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of(), @JsonProperty("model_max_budget") @ExcludeMissing - modelMaxBudget: JsonValue = JsonMissing.of(), + modelMaxBudget: JsonField = JsonMissing.of(), @JsonProperty("model_rpm_limit") @ExcludeMissing - modelRpmLimit: JsonValue = JsonMissing.of(), + modelRpmLimit: JsonField = JsonMissing.of(), @JsonProperty("model_tpm_limit") @ExcludeMissing - modelTpmLimit: JsonValue = JsonMissing.of(), + modelTpmLimit: JsonField = JsonMissing.of(), @JsonProperty("models") @ExcludeMissing models: JsonField> = JsonMissing.of(), - @JsonProperty("permissions") @ExcludeMissing permissions: JsonValue = JsonMissing.of(), + @JsonProperty("object_permission") + @ExcludeMissing + objectPermission: JsonField = JsonMissing.of(), + @JsonProperty("permissions") + @ExcludeMissing + permissions: JsonField = JsonMissing.of(), + @JsonProperty("prompts") + @ExcludeMissing + prompts: JsonField> = JsonMissing.of(), + @JsonProperty("rotation_interval") + @ExcludeMissing + rotationInterval: JsonField = JsonMissing.of(), + @JsonProperty("router_settings") + @ExcludeMissing + routerSettings: JsonField = JsonMissing.of(), @JsonProperty("rpm_limit") @ExcludeMissing rpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("rpm_limit_type") + @ExcludeMissing + rpmLimitType: JsonField = JsonMissing.of(), @JsonProperty("spend") @ExcludeMissing spend: JsonField = JsonMissing.of(), @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), @JsonProperty("team_id") @ExcludeMissing teamId: JsonField = JsonMissing.of(), @@ -1061,11 +1689,18 @@ private constructor( @ExcludeMissing tempBudgetIncrease: JsonField = JsonMissing.of(), @JsonProperty("tpm_limit") @ExcludeMissing tpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("tpm_limit_type") + @ExcludeMissing + tpmLimitType: JsonField = JsonMissing.of(), @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), ) : this( key, aliases, allowedCacheControls, + allowedPassthroughRoutes, + allowedRoutes, + allowedVectorStoreIndexes, + autoRotate, blocked, budgetDuration, budgetId, @@ -1081,14 +1716,20 @@ private constructor( modelRpmLimit, modelTpmLimit, models, + objectPermission, permissions, + prompts, + rotationInterval, + routerSettings, rpmLimit, + rpmLimitType, spend, tags, teamId, tempBudgetExpiry, tempBudgetIncrease, tpmLimit, + tpmLimitType, userId, mutableMapOf(), ) @@ -1099,146 +1740,232 @@ private constructor( */ fun key(): String = key.getRequired("key") - @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonValue = aliases + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aliases(): Optional = aliases.getOptional("aliases") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun allowedCacheControls(): Optional> = - Optional.ofNullable(allowedCacheControls.getNullable("allowed_cache_controls")) + allowedCacheControls.getOptional("allowed_cache_controls") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedPassthroughRoutes(): Optional> = + allowedPassthroughRoutes.getOptional("allowed_passthrough_routes") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedRoutes(): Optional> = allowedRoutes.getOptional("allowed_routes") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedVectorStoreIndexes(): Optional> = + allowedVectorStoreIndexes.getOptional("allowed_vector_store_indexes") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun autoRotate(): Optional = autoRotate.getOptional("auto_rotate") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun blocked(): Optional = Optional.ofNullable(blocked.getNullable("blocked")) + fun blocked(): Optional = blocked.getOptional("blocked") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetDuration(): Optional = - Optional.ofNullable(budgetDuration.getNullable("budget_duration")) + fun budgetDuration(): Optional = budgetDuration.getOptional("budget_duration") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetId(): Optional = Optional.ofNullable(budgetId.getNullable("budget_id")) + fun budgetId(): Optional = budgetId.getOptional("budget_id") - @JsonProperty("config") @ExcludeMissing fun _config(): JsonValue = config + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun config(): Optional = config.getOptional("config") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun duration(): Optional = Optional.ofNullable(duration.getNullable("duration")) + fun duration(): Optional = duration.getOptional("duration") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun enforcedParams(): Optional> = - Optional.ofNullable(enforcedParams.getNullable("enforced_params")) + fun enforcedParams(): Optional> = enforcedParams.getOptional("enforced_params") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun guardrails(): Optional> = - Optional.ofNullable(guardrails.getNullable("guardrails")) + fun guardrails(): Optional> = guardrails.getOptional("guardrails") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun keyAlias(): Optional = Optional.ofNullable(keyAlias.getNullable("key_alias")) + fun keyAlias(): Optional = keyAlias.getOptional("key_alias") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun maxBudget(): Optional = Optional.ofNullable(maxBudget.getNullable("max_budget")) + fun maxBudget(): Optional = maxBudget.getOptional("max_budget") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun maxParallelRequests(): Optional = - Optional.ofNullable(maxParallelRequests.getNullable("max_parallel_requests")) + maxParallelRequests.getOptional("max_parallel_requests") - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonValue = metadata + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") - @JsonProperty("model_max_budget") - @ExcludeMissing - fun _modelMaxBudget(): JsonValue = modelMaxBudget + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelMaxBudget(): Optional = + modelMaxBudget.getOptional("model_max_budget") - @JsonProperty("model_rpm_limit") - @ExcludeMissing - fun _modelRpmLimit(): JsonValue = modelRpmLimit + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelRpmLimit(): Optional = modelRpmLimit.getOptional("model_rpm_limit") - @JsonProperty("model_tpm_limit") - @ExcludeMissing - fun _modelTpmLimit(): JsonValue = modelTpmLimit + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelTpmLimit(): Optional = modelTpmLimit.getOptional("model_tpm_limit") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun models(): Optional> = models.getOptional("models") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun objectPermission(): Optional = + objectPermission.getOptional("object_permission") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun permissions(): Optional = permissions.getOptional("permissions") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun models(): Optional> = Optional.ofNullable(models.getNullable("models")) + fun prompts(): Optional> = prompts.getOptional("prompts") - @JsonProperty("permissions") @ExcludeMissing fun _permissions(): JsonValue = permissions + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rotationInterval(): Optional = rotationInterval.getOptional("rotation_interval") + + /** + * Set of params that you can modify via `router.update_settings()`. + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routerSettings(): Optional = + routerSettings.getOptional("router_settings") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rpmLimit(): Optional = rpmLimit.getOptional("rpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rpmLimit(): Optional = Optional.ofNullable(rpmLimit.getNullable("rpm_limit")) + fun rpmLimitType(): Optional = rpmLimitType.getOptional("rpm_limit_type") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spend(): Optional = Optional.ofNullable(spend.getNullable("spend")) + fun spend(): Optional = spend.getOptional("spend") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tags(): Optional> = Optional.ofNullable(tags.getNullable("tags")) + fun tags(): Optional> = tags.getOptional("tags") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun teamId(): Optional = Optional.ofNullable(teamId.getNullable("team_id")) + fun teamId(): Optional = teamId.getOptional("team_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun tempBudgetExpiry(): Optional = - Optional.ofNullable(tempBudgetExpiry.getNullable("temp_budget_expiry")) + tempBudgetExpiry.getOptional("temp_budget_expiry") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun tempBudgetIncrease(): Optional = - Optional.ofNullable(tempBudgetIncrease.getNullable("temp_budget_increase")) + tempBudgetIncrease.getOptional("temp_budget_increase") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tpmLimit(): Optional = tpmLimit.getOptional("tpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tpmLimit(): Optional = Optional.ofNullable(tpmLimit.getNullable("tpm_limit")) + fun tpmLimitType(): Optional = tpmLimitType.getOptional("tpm_limit_type") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) + fun userId(): Optional = userId.getOptional("user_id") /** * Returns the raw JSON value of [key]. @@ -1247,6 +1974,13 @@ private constructor( */ @JsonProperty("key") @ExcludeMissing fun _key(): JsonField = key + /** + * Returns the raw JSON value of [aliases]. + * + * Unlike [aliases], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonField = aliases + /** * Returns the raw JSON value of [allowedCacheControls]. * @@ -1257,6 +1991,46 @@ private constructor( @ExcludeMissing fun _allowedCacheControls(): JsonField> = allowedCacheControls + /** + * Returns the raw JSON value of [allowedPassthroughRoutes]. + * + * Unlike [allowedPassthroughRoutes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("allowed_passthrough_routes") + @ExcludeMissing + fun _allowedPassthroughRoutes(): JsonField> = allowedPassthroughRoutes + + /** + * Returns the raw JSON value of [allowedRoutes]. + * + * Unlike [allowedRoutes], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("allowed_routes") + @ExcludeMissing + fun _allowedRoutes(): JsonField> = allowedRoutes + + /** + * Returns the raw JSON value of [allowedVectorStoreIndexes]. + * + * Unlike [allowedVectorStoreIndexes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("allowed_vector_store_indexes") + @ExcludeMissing + fun _allowedVectorStoreIndexes(): JsonField> = + allowedVectorStoreIndexes + + /** + * Returns the raw JSON value of [autoRotate]. + * + * Unlike [autoRotate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("auto_rotate") + @ExcludeMissing + fun _autoRotate(): JsonField = autoRotate + /** * Returns the raw JSON value of [blocked]. * @@ -1281,6 +2055,13 @@ private constructor( */ @JsonProperty("budget_id") @ExcludeMissing fun _budgetId(): JsonField = budgetId + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config") @ExcludeMissing fun _config(): JsonField = config + /** * Returns the raw JSON value of [duration]. * @@ -1332,44 +2113,137 @@ private constructor( fun _maxParallelRequests(): JsonField = maxParallelRequests /** - * Returns the raw JSON value of [models]. + * Returns the raw JSON value of [metadata]. * - * Unlike [models], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("models") @ExcludeMissing fun _models(): JsonField> = models + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata /** - * Returns the raw JSON value of [rpmLimit]. + * Returns the raw JSON value of [modelMaxBudget]. * - * Unlike [rpmLimit], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [modelMaxBudget], this method doesn't throw if the JSON field has an unexpected + * type. */ - @JsonProperty("rpm_limit") @ExcludeMissing fun _rpmLimit(): JsonField = rpmLimit + @JsonProperty("model_max_budget") + @ExcludeMissing + fun _modelMaxBudget(): JsonField = modelMaxBudget /** - * Returns the raw JSON value of [spend]. + * Returns the raw JSON value of [modelRpmLimit]. * - * Unlike [spend], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [modelRpmLimit], this method doesn't throw if the JSON field has an unexpected + * type. */ - @JsonProperty("spend") @ExcludeMissing fun _spend(): JsonField = spend + @JsonProperty("model_rpm_limit") + @ExcludeMissing + fun _modelRpmLimit(): JsonField = modelRpmLimit /** - * Returns the raw JSON value of [tags]. + * Returns the raw JSON value of [modelTpmLimit]. * - * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [modelTpmLimit], this method doesn't throw if the JSON field has an unexpected + * type. */ - @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + @JsonProperty("model_tpm_limit") + @ExcludeMissing + fun _modelTpmLimit(): JsonField = modelTpmLimit /** - * Returns the raw JSON value of [teamId]. + * Returns the raw JSON value of [models]. * - * Unlike [teamId], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [models], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("team_id") @ExcludeMissing fun _teamId(): JsonField = teamId + @JsonProperty("models") @ExcludeMissing fun _models(): JsonField> = models /** - * Returns the raw JSON value of [tempBudgetExpiry]. + * Returns the raw JSON value of [objectPermission]. * - * Unlike [tempBudgetExpiry], this method doesn't throw if the JSON field has an unexpected + * Unlike [objectPermission], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("object_permission") + @ExcludeMissing + fun _objectPermission(): JsonField = objectPermission + + /** + * Returns the raw JSON value of [permissions]. + * + * Unlike [permissions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permissions") + @ExcludeMissing + fun _permissions(): JsonField = permissions + + /** + * Returns the raw JSON value of [prompts]. + * + * Unlike [prompts], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prompts") @ExcludeMissing fun _prompts(): JsonField> = prompts + + /** + * Returns the raw JSON value of [rotationInterval]. + * + * Unlike [rotationInterval], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("rotation_interval") + @ExcludeMissing + fun _rotationInterval(): JsonField = rotationInterval + + /** + * Returns the raw JSON value of [routerSettings]. + * + * Unlike [routerSettings], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("router_settings") + @ExcludeMissing + fun _routerSettings(): JsonField = routerSettings + + /** + * Returns the raw JSON value of [rpmLimit]. + * + * Unlike [rpmLimit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("rpm_limit") @ExcludeMissing fun _rpmLimit(): JsonField = rpmLimit + + /** + * Returns the raw JSON value of [rpmLimitType]. + * + * Unlike [rpmLimitType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("rpm_limit_type") + @ExcludeMissing + fun _rpmLimitType(): JsonField = rpmLimitType + + /** + * Returns the raw JSON value of [spend]. + * + * Unlike [spend], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("spend") @ExcludeMissing fun _spend(): JsonField = spend + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tags") @ExcludeMissing fun _tags(): JsonField> = tags + + /** + * Returns the raw JSON value of [teamId]. + * + * Unlike [teamId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("team_id") @ExcludeMissing fun _teamId(): JsonField = teamId + + /** + * Returns the raw JSON value of [tempBudgetExpiry]. + * + * Unlike [tempBudgetExpiry], this method doesn't throw if the JSON field has an unexpected * type. */ @JsonProperty("temp_budget_expiry") @@ -1393,6 +2267,16 @@ private constructor( */ @JsonProperty("tpm_limit") @ExcludeMissing fun _tpmLimit(): JsonField = tpmLimit + /** + * Returns the raw JSON value of [tpmLimitType]. + * + * Unlike [tpmLimitType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tpm_limit_type") + @ExcludeMissing + fun _tpmLimitType(): JsonField = tpmLimitType + /** * Returns the raw JSON value of [userId]. * @@ -1429,31 +2313,43 @@ private constructor( class Builder internal constructor() { private var key: JsonField? = null - private var aliases: JsonValue = JsonMissing.of() + private var aliases: JsonField = JsonMissing.of() private var allowedCacheControls: JsonField>? = null + private var allowedPassthroughRoutes: JsonField>? = null + private var allowedRoutes: JsonField>? = null + private var allowedVectorStoreIndexes: + JsonField>? = + null + private var autoRotate: JsonField = JsonMissing.of() private var blocked: JsonField = JsonMissing.of() private var budgetDuration: JsonField = JsonMissing.of() private var budgetId: JsonField = JsonMissing.of() - private var config: JsonValue = JsonMissing.of() + private var config: JsonField = JsonMissing.of() private var duration: JsonField = JsonMissing.of() private var enforcedParams: JsonField>? = null private var guardrails: JsonField>? = null private var keyAlias: JsonField = JsonMissing.of() private var maxBudget: JsonField = JsonMissing.of() private var maxParallelRequests: JsonField = JsonMissing.of() - private var metadata: JsonValue = JsonMissing.of() - private var modelMaxBudget: JsonValue = JsonMissing.of() - private var modelRpmLimit: JsonValue = JsonMissing.of() - private var modelTpmLimit: JsonValue = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var modelMaxBudget: JsonField = JsonMissing.of() + private var modelRpmLimit: JsonField = JsonMissing.of() + private var modelTpmLimit: JsonField = JsonMissing.of() private var models: JsonField>? = null - private var permissions: JsonValue = JsonMissing.of() + private var objectPermission: JsonField = JsonMissing.of() + private var permissions: JsonField = JsonMissing.of() + private var prompts: JsonField>? = null + private var rotationInterval: JsonField = JsonMissing.of() + private var routerSettings: JsonField = JsonMissing.of() private var rpmLimit: JsonField = JsonMissing.of() + private var rpmLimitType: JsonField = JsonMissing.of() private var spend: JsonField = JsonMissing.of() private var tags: JsonField>? = null private var teamId: JsonField = JsonMissing.of() private var tempBudgetExpiry: JsonField = JsonMissing.of() private var tempBudgetIncrease: JsonField = JsonMissing.of() private var tpmLimit: JsonField = JsonMissing.of() + private var tpmLimitType: JsonField = JsonMissing.of() private var userId: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @@ -1462,6 +2358,11 @@ private constructor( key = body.key aliases = body.aliases allowedCacheControls = body.allowedCacheControls.map { it.toMutableList() } + allowedPassthroughRoutes = body.allowedPassthroughRoutes.map { it.toMutableList() } + allowedRoutes = body.allowedRoutes.map { it.toMutableList() } + allowedVectorStoreIndexes = + body.allowedVectorStoreIndexes.map { it.toMutableList() } + autoRotate = body.autoRotate blocked = body.blocked budgetDuration = body.budgetDuration budgetId = body.budgetId @@ -1477,14 +2378,20 @@ private constructor( modelRpmLimit = body.modelRpmLimit modelTpmLimit = body.modelTpmLimit models = body.models.map { it.toMutableList() } + objectPermission = body.objectPermission permissions = body.permissions + prompts = body.prompts.map { it.toMutableList() } + rotationInterval = body.rotationInterval + routerSettings = body.routerSettings rpmLimit = body.rpmLimit + rpmLimitType = body.rpmLimitType spend = body.spend tags = body.tags.map { it.toMutableList() } teamId = body.teamId tempBudgetExpiry = body.tempBudgetExpiry tempBudgetIncrease = body.tempBudgetIncrease tpmLimit = body.tpmLimit + tpmLimitType = body.tpmLimitType userId = body.userId additionalProperties = body.additionalProperties.toMutableMap() } @@ -1500,7 +2407,19 @@ private constructor( */ fun key(key: JsonField) = apply { this.key = key } - fun aliases(aliases: JsonValue) = apply { this.aliases = aliases } + fun aliases(aliases: Aliases?) = aliases(JsonField.ofNullable(aliases)) + + /** Alias for calling [Builder.aliases] with `aliases.orElse(null)`. */ + fun aliases(aliases: Optional) = aliases(aliases.getOrNull()) + + /** + * Sets [Builder.aliases] to an arbitrary JSON value. + * + * You should usually call [Builder.aliases] with a well-typed [Aliases] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun aliases(aliases: JsonField) = apply { this.aliases = aliases } fun allowedCacheControls(allowedCacheControls: List?) = allowedCacheControls(JsonField.ofNullable(allowedCacheControls)) @@ -1535,6 +2454,131 @@ private constructor( } } + fun allowedPassthroughRoutes(allowedPassthroughRoutes: List?) = + allowedPassthroughRoutes(JsonField.ofNullable(allowedPassthroughRoutes)) + + /** + * Alias for calling [Builder.allowedPassthroughRoutes] with + * `allowedPassthroughRoutes.orElse(null)`. + */ + fun allowedPassthroughRoutes(allowedPassthroughRoutes: Optional>) = + allowedPassthroughRoutes(allowedPassthroughRoutes.getOrNull()) + + /** + * Sets [Builder.allowedPassthroughRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedPassthroughRoutes] with a well-typed + * `List` value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun allowedPassthroughRoutes(allowedPassthroughRoutes: JsonField>) = + apply { + this.allowedPassthroughRoutes = + allowedPassthroughRoutes.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [allowedPassthroughRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedPassthroughRoute(allowedPassthroughRoute: JsonValue) = apply { + allowedPassthroughRoutes = + (allowedPassthroughRoutes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedPassthroughRoutes", it).add(allowedPassthroughRoute) + } + } + + fun allowedRoutes(allowedRoutes: List?) = + allowedRoutes(JsonField.ofNullable(allowedRoutes)) + + /** Alias for calling [Builder.allowedRoutes] with `allowedRoutes.orElse(null)`. */ + fun allowedRoutes(allowedRoutes: Optional>) = + allowedRoutes(allowedRoutes.getOrNull()) + + /** + * Sets [Builder.allowedRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedRoutes] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun allowedRoutes(allowedRoutes: JsonField>) = apply { + this.allowedRoutes = allowedRoutes.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [allowedRoutes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedRoute(allowedRoute: JsonValue) = apply { + allowedRoutes = + (allowedRoutes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedRoutes", it).add(allowedRoute) + } + } + + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: List? + ) = allowedVectorStoreIndexes(JsonField.ofNullable(allowedVectorStoreIndexes)) + + /** + * Alias for calling [Builder.allowedVectorStoreIndexes] with + * `allowedVectorStoreIndexes.orElse(null)`. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: Optional> + ) = allowedVectorStoreIndexes(allowedVectorStoreIndexes.getOrNull()) + + /** + * Sets [Builder.allowedVectorStoreIndexes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedVectorStoreIndexes] with a well-typed + * `List` value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: JsonField> + ) = apply { + this.allowedVectorStoreIndexes = + allowedVectorStoreIndexes.map { it.toMutableList() } + } + + /** + * Adds a single [AllowedVectorStoreIndex] to [allowedVectorStoreIndexes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedVectorStoreIndex(allowedVectorStoreIndex: AllowedVectorStoreIndex) = + apply { + allowedVectorStoreIndexes = + (allowedVectorStoreIndexes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedVectorStoreIndexes", it).add(allowedVectorStoreIndex) + } + } + + fun autoRotate(autoRotate: Boolean?) = autoRotate(JsonField.ofNullable(autoRotate)) + + /** + * Alias for [Builder.autoRotate]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun autoRotate(autoRotate: Boolean) = autoRotate(autoRotate as Boolean?) + + /** Alias for calling [Builder.autoRotate] with `autoRotate.orElse(null)`. */ + fun autoRotate(autoRotate: Optional) = autoRotate(autoRotate.getOrNull()) + + /** + * Sets [Builder.autoRotate] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRotate] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun autoRotate(autoRotate: JsonField) = apply { this.autoRotate = autoRotate } + fun blocked(blocked: Boolean?) = blocked(JsonField.ofNullable(blocked)) /** @@ -1588,7 +2632,19 @@ private constructor( */ fun budgetId(budgetId: JsonField) = apply { this.budgetId = budgetId } - fun config(config: JsonValue) = apply { this.config = config } + fun config(config: Config?) = config(JsonField.ofNullable(config)) + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [Config] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun config(config: JsonField) = apply { this.config = config } fun duration(duration: String?) = duration(JsonField.ofNullable(duration)) @@ -1726,17 +2782,71 @@ private constructor( this.maxParallelRequests = maxParallelRequests } - fun metadata(metadata: JsonValue) = apply { this.metadata = metadata } + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) - fun modelMaxBudget(modelMaxBudget: JsonValue) = apply { + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun modelMaxBudget(modelMaxBudget: ModelMaxBudget?) = + modelMaxBudget(JsonField.ofNullable(modelMaxBudget)) + + /** Alias for calling [Builder.modelMaxBudget] with `modelMaxBudget.orElse(null)`. */ + fun modelMaxBudget(modelMaxBudget: Optional) = + modelMaxBudget(modelMaxBudget.getOrNull()) + + /** + * Sets [Builder.modelMaxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.modelMaxBudget] with a well-typed [ModelMaxBudget] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun modelMaxBudget(modelMaxBudget: JsonField) = apply { this.modelMaxBudget = modelMaxBudget } - fun modelRpmLimit(modelRpmLimit: JsonValue) = apply { + fun modelRpmLimit(modelRpmLimit: ModelRpmLimit?) = + modelRpmLimit(JsonField.ofNullable(modelRpmLimit)) + + /** Alias for calling [Builder.modelRpmLimit] with `modelRpmLimit.orElse(null)`. */ + fun modelRpmLimit(modelRpmLimit: Optional) = + modelRpmLimit(modelRpmLimit.getOrNull()) + + /** + * Sets [Builder.modelRpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.modelRpmLimit] with a well-typed [ModelRpmLimit] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun modelRpmLimit(modelRpmLimit: JsonField) = apply { this.modelRpmLimit = modelRpmLimit } - fun modelTpmLimit(modelTpmLimit: JsonValue) = apply { + fun modelTpmLimit(modelTpmLimit: ModelTpmLimit?) = + modelTpmLimit(JsonField.ofNullable(modelTpmLimit)) + + /** Alias for calling [Builder.modelTpmLimit] with `modelTpmLimit.orElse(null)`. */ + fun modelTpmLimit(modelTpmLimit: Optional) = + modelTpmLimit(modelTpmLimit.getOrNull()) + + /** + * Sets [Builder.modelTpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.modelTpmLimit] with a well-typed [ModelTpmLimit] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun modelTpmLimit(modelTpmLimit: JsonField) = apply { this.modelTpmLimit = modelTpmLimit } @@ -1768,7 +2878,110 @@ private constructor( } } - fun permissions(permissions: JsonValue) = apply { this.permissions = permissions } + fun objectPermission(objectPermission: ObjectPermission?) = + objectPermission(JsonField.ofNullable(objectPermission)) + + /** + * Alias for calling [Builder.objectPermission] with `objectPermission.orElse(null)`. + */ + fun objectPermission(objectPermission: Optional) = + objectPermission(objectPermission.getOrNull()) + + /** + * Sets [Builder.objectPermission] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermission] with a well-typed + * [ObjectPermission] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun objectPermission(objectPermission: JsonField) = apply { + this.objectPermission = objectPermission + } + + fun permissions(permissions: Permissions?) = + permissions(JsonField.ofNullable(permissions)) + + /** Alias for calling [Builder.permissions] with `permissions.orElse(null)`. */ + fun permissions(permissions: Optional) = + permissions(permissions.getOrNull()) + + /** + * Sets [Builder.permissions] to an arbitrary JSON value. + * + * You should usually call [Builder.permissions] with a well-typed [Permissions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun permissions(permissions: JsonField) = apply { + this.permissions = permissions + } + + fun prompts(prompts: List?) = prompts(JsonField.ofNullable(prompts)) + + /** Alias for calling [Builder.prompts] with `prompts.orElse(null)`. */ + fun prompts(prompts: Optional>) = prompts(prompts.getOrNull()) + + /** + * Sets [Builder.prompts] to an arbitrary JSON value. + * + * You should usually call [Builder.prompts] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun prompts(prompts: JsonField>) = apply { + this.prompts = prompts.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [prompts]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addPrompt(prompt: String) = apply { + prompts = + (prompts ?: JsonField.of(mutableListOf())).also { + checkKnown("prompts", it).add(prompt) + } + } + + fun rotationInterval(rotationInterval: String?) = + rotationInterval(JsonField.ofNullable(rotationInterval)) + + /** + * Alias for calling [Builder.rotationInterval] with `rotationInterval.orElse(null)`. + */ + fun rotationInterval(rotationInterval: Optional) = + rotationInterval(rotationInterval.getOrNull()) + + /** + * Sets [Builder.rotationInterval] to an arbitrary JSON value. + * + * You should usually call [Builder.rotationInterval] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rotationInterval(rotationInterval: JsonField) = apply { + this.rotationInterval = rotationInterval + } + + /** Set of params that you can modify via `router.update_settings()`. */ + fun routerSettings(routerSettings: RouterSettings?) = + routerSettings(JsonField.ofNullable(routerSettings)) + + /** Alias for calling [Builder.routerSettings] with `routerSettings.orElse(null)`. */ + fun routerSettings(routerSettings: Optional) = + routerSettings(routerSettings.getOrNull()) + + /** + * Sets [Builder.routerSettings] to an arbitrary JSON value. + * + * You should usually call [Builder.routerSettings] with a well-typed [RouterSettings] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun routerSettings(routerSettings: JsonField) = apply { + this.routerSettings = routerSettings + } fun rpmLimit(rpmLimit: Long?) = rpmLimit(JsonField.ofNullable(rpmLimit)) @@ -1791,6 +3004,24 @@ private constructor( */ fun rpmLimit(rpmLimit: JsonField) = apply { this.rpmLimit = rpmLimit } + fun rpmLimitType(rpmLimitType: RpmLimitType?) = + rpmLimitType(JsonField.ofNullable(rpmLimitType)) + + /** Alias for calling [Builder.rpmLimitType] with `rpmLimitType.orElse(null)`. */ + fun rpmLimitType(rpmLimitType: Optional) = + rpmLimitType(rpmLimitType.getOrNull()) + + /** + * Sets [Builder.rpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.rpmLimitType] with a well-typed [RpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rpmLimitType(rpmLimitType: JsonField) = apply { + this.rpmLimitType = rpmLimitType + } + fun spend(spend: Double?) = spend(JsonField.ofNullable(spend)) /** @@ -1922,6 +3153,24 @@ private constructor( */ fun tpmLimit(tpmLimit: JsonField) = apply { this.tpmLimit = tpmLimit } + fun tpmLimitType(tpmLimitType: TpmLimitType?) = + tpmLimitType(JsonField.ofNullable(tpmLimitType)) + + /** Alias for calling [Builder.tpmLimitType] with `tpmLimitType.orElse(null)`. */ + fun tpmLimitType(tpmLimitType: Optional) = + tpmLimitType(tpmLimitType.getOrNull()) + + /** + * Sets [Builder.tpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.tpmLimitType] with a well-typed [TpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tpmLimitType(tpmLimitType: JsonField) = apply { + this.tpmLimitType = tpmLimitType + } + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ @@ -1972,6 +3221,10 @@ private constructor( checkRequired("key", key), aliases, (allowedCacheControls ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedPassthroughRoutes ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedRoutes ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedVectorStoreIndexes ?: JsonMissing.of()).map { it.toImmutable() }, + autoRotate, blocked, budgetDuration, budgetId, @@ -1987,14 +3240,20 @@ private constructor( modelRpmLimit, modelTpmLimit, (models ?: JsonMissing.of()).map { it.toImmutable() }, + objectPermission, permissions, + (prompts ?: JsonMissing.of()).map { it.toImmutable() }, + rotationInterval, + routerSettings, rpmLimit, + rpmLimitType, spend, (tags ?: JsonMissing.of()).map { it.toImmutable() }, teamId, tempBudgetExpiry, tempBudgetIncrease, tpmLimit, + tpmLimitType, userId, additionalProperties.toMutableMap(), ) @@ -2008,44 +3267,3316 @@ private constructor( } key() + aliases().ifPresent { it.validate() } allowedCacheControls() + allowedPassthroughRoutes() + allowedRoutes() + allowedVectorStoreIndexes().ifPresent { it.forEach { it.validate() } } + autoRotate() blocked() budgetDuration() budgetId() + config().ifPresent { it.validate() } duration() enforcedParams() guardrails() keyAlias() maxBudget() maxParallelRequests() + metadata().ifPresent { it.validate() } + modelMaxBudget().ifPresent { it.validate() } + modelRpmLimit().ifPresent { it.validate() } + modelTpmLimit().ifPresent { it.validate() } models() + objectPermission().ifPresent { it.validate() } + permissions().ifPresent { it.validate() } + prompts() + rotationInterval() + routerSettings().ifPresent { it.validate() } rpmLimit() + rpmLimitType().ifPresent { it.validate() } spend() tags() teamId() tempBudgetExpiry() tempBudgetIncrease() tpmLimit() + tpmLimitType().ifPresent { it.validate() } userId() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (key.asKnown().isPresent) 1 else 0) + + (aliases.asKnown().getOrNull()?.validity() ?: 0) + + (allowedCacheControls.asKnown().getOrNull()?.size ?: 0) + + (allowedPassthroughRoutes.asKnown().getOrNull()?.size ?: 0) + + (allowedRoutes.asKnown().getOrNull()?.size ?: 0) + + (allowedVectorStoreIndexes.asKnown().getOrNull()?.sumOf { it.validity().toInt() } + ?: 0) + + (if (autoRotate.asKnown().isPresent) 1 else 0) + + (if (blocked.asKnown().isPresent) 1 else 0) + + (if (budgetDuration.asKnown().isPresent) 1 else 0) + + (if (budgetId.asKnown().isPresent) 1 else 0) + + (config.asKnown().getOrNull()?.validity() ?: 0) + + (if (duration.asKnown().isPresent) 1 else 0) + + (enforcedParams.asKnown().getOrNull()?.size ?: 0) + + (guardrails.asKnown().getOrNull()?.size ?: 0) + + (if (keyAlias.asKnown().isPresent) 1 else 0) + + (if (maxBudget.asKnown().isPresent) 1 else 0) + + (if (maxParallelRequests.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (modelMaxBudget.asKnown().getOrNull()?.validity() ?: 0) + + (modelRpmLimit.asKnown().getOrNull()?.validity() ?: 0) + + (modelTpmLimit.asKnown().getOrNull()?.validity() ?: 0) + + (models.asKnown().getOrNull()?.size ?: 0) + + (objectPermission.asKnown().getOrNull()?.validity() ?: 0) + + (permissions.asKnown().getOrNull()?.validity() ?: 0) + + (prompts.asKnown().getOrNull()?.size ?: 0) + + (if (rotationInterval.asKnown().isPresent) 1 else 0) + + (routerSettings.asKnown().getOrNull()?.validity() ?: 0) + + (if (rpmLimit.asKnown().isPresent) 1 else 0) + + (rpmLimitType.asKnown().getOrNull()?.validity() ?: 0) + + (if (spend.asKnown().isPresent) 1 else 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + (if (teamId.asKnown().isPresent) 1 else 0) + + (if (tempBudgetExpiry.asKnown().isPresent) 1 else 0) + + (if (tempBudgetIncrease.asKnown().isPresent) 1 else 0) + + (if (tpmLimit.asKnown().isPresent) 1 else 0) + + (tpmLimitType.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && key == other.key && aliases == other.aliases && allowedCacheControls == other.allowedCacheControls && blocked == other.blocked && budgetDuration == other.budgetDuration && budgetId == other.budgetId && config == other.config && duration == other.duration && enforcedParams == other.enforcedParams && guardrails == other.guardrails && keyAlias == other.keyAlias && maxBudget == other.maxBudget && maxParallelRequests == other.maxParallelRequests && metadata == other.metadata && modelMaxBudget == other.modelMaxBudget && modelRpmLimit == other.modelRpmLimit && modelTpmLimit == other.modelTpmLimit && models == other.models && permissions == other.permissions && rpmLimit == other.rpmLimit && spend == other.spend && tags == other.tags && teamId == other.teamId && tempBudgetExpiry == other.tempBudgetExpiry && tempBudgetIncrease == other.tempBudgetIncrease && tpmLimit == other.tpmLimit && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Body && + key == other.key && + aliases == other.aliases && + allowedCacheControls == other.allowedCacheControls && + allowedPassthroughRoutes == other.allowedPassthroughRoutes && + allowedRoutes == other.allowedRoutes && + allowedVectorStoreIndexes == other.allowedVectorStoreIndexes && + autoRotate == other.autoRotate && + blocked == other.blocked && + budgetDuration == other.budgetDuration && + budgetId == other.budgetId && + config == other.config && + duration == other.duration && + enforcedParams == other.enforcedParams && + guardrails == other.guardrails && + keyAlias == other.keyAlias && + maxBudget == other.maxBudget && + maxParallelRequests == other.maxParallelRequests && + metadata == other.metadata && + modelMaxBudget == other.modelMaxBudget && + modelRpmLimit == other.modelRpmLimit && + modelTpmLimit == other.modelTpmLimit && + models == other.models && + objectPermission == other.objectPermission && + permissions == other.permissions && + prompts == other.prompts && + rotationInterval == other.rotationInterval && + routerSettings == other.routerSettings && + rpmLimit == other.rpmLimit && + rpmLimitType == other.rpmLimitType && + spend == other.spend && + tags == other.tags && + teamId == other.teamId && + tempBudgetExpiry == other.tempBudgetExpiry && + tempBudgetIncrease == other.tempBudgetIncrease && + tpmLimit == other.tpmLimit && + tpmLimitType == other.tpmLimitType && + userId == other.userId && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(key, aliases, allowedCacheControls, blocked, budgetDuration, budgetId, config, duration, enforcedParams, guardrails, keyAlias, maxBudget, maxParallelRequests, metadata, modelMaxBudget, modelRpmLimit, modelTpmLimit, models, permissions, rpmLimit, spend, tags, teamId, tempBudgetExpiry, tempBudgetIncrease, tpmLimit, userId, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + key, + aliases, + allowedCacheControls, + allowedPassthroughRoutes, + allowedRoutes, + allowedVectorStoreIndexes, + autoRotate, + blocked, + budgetDuration, + budgetId, + config, + duration, + enforcedParams, + guardrails, + keyAlias, + maxBudget, + maxParallelRequests, + metadata, + modelMaxBudget, + modelRpmLimit, + modelTpmLimit, + models, + objectPermission, + permissions, + prompts, + rotationInterval, + routerSettings, + rpmLimit, + rpmLimitType, + spend, + tags, + teamId, + tempBudgetExpiry, + tempBudgetIncrease, + tpmLimit, + tpmLimitType, + userId, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "Body{key=$key, aliases=$aliases, allowedCacheControls=$allowedCacheControls, blocked=$blocked, budgetDuration=$budgetDuration, budgetId=$budgetId, config=$config, duration=$duration, enforcedParams=$enforcedParams, guardrails=$guardrails, keyAlias=$keyAlias, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelRpmLimit=$modelRpmLimit, modelTpmLimit=$modelTpmLimit, models=$models, permissions=$permissions, rpmLimit=$rpmLimit, spend=$spend, tags=$tags, teamId=$teamId, tempBudgetExpiry=$tempBudgetExpiry, tempBudgetIncrease=$tempBudgetIncrease, tpmLimit=$tpmLimit, userId=$userId, additionalProperties=$additionalProperties}" + "Body{key=$key, aliases=$aliases, allowedCacheControls=$allowedCacheControls, allowedPassthroughRoutes=$allowedPassthroughRoutes, allowedRoutes=$allowedRoutes, allowedVectorStoreIndexes=$allowedVectorStoreIndexes, autoRotate=$autoRotate, blocked=$blocked, budgetDuration=$budgetDuration, budgetId=$budgetId, config=$config, duration=$duration, enforcedParams=$enforcedParams, guardrails=$guardrails, keyAlias=$keyAlias, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelRpmLimit=$modelRpmLimit, modelTpmLimit=$modelTpmLimit, models=$models, objectPermission=$objectPermission, permissions=$permissions, prompts=$prompts, rotationInterval=$rotationInterval, routerSettings=$routerSettings, rpmLimit=$rpmLimit, rpmLimitType=$rpmLimitType, spend=$spend, tags=$tags, teamId=$teamId, tempBudgetExpiry=$tempBudgetExpiry, tempBudgetIncrease=$tempBudgetIncrease, tpmLimit=$tpmLimit, tpmLimitType=$tpmLimitType, userId=$userId, additionalProperties=$additionalProperties}" + } + + class Aliases + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Aliases]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Aliases]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aliases: Aliases) = apply { + additionalProperties = aliases.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Aliases]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Aliases = Aliases(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Aliases = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Aliases && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Aliases{additionalProperties=$additionalProperties}" + } + + class AllowedVectorStoreIndex + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val indexName: JsonField, + private val indexPermissions: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("index_name") + @ExcludeMissing + indexName: JsonField = JsonMissing.of(), + @JsonProperty("index_permissions") + @ExcludeMissing + indexPermissions: JsonField> = JsonMissing.of(), + ) : this(indexName, indexPermissions, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun indexName(): String = indexName.getRequired("index_name") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun indexPermissions(): List = + indexPermissions.getRequired("index_permissions") + + /** + * Returns the raw JSON value of [indexName]. + * + * Unlike [indexName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("index_name") @ExcludeMissing fun _indexName(): JsonField = indexName + + /** + * Returns the raw JSON value of [indexPermissions]. + * + * Unlike [indexPermissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("index_permissions") + @ExcludeMissing + fun _indexPermissions(): JsonField> = indexPermissions + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AllowedVectorStoreIndex]. + * + * The following fields are required: + * ```java + * .indexName() + * .indexPermissions() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AllowedVectorStoreIndex]. */ + class Builder internal constructor() { + + private var indexName: JsonField? = null + private var indexPermissions: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(allowedVectorStoreIndex: AllowedVectorStoreIndex) = apply { + indexName = allowedVectorStoreIndex.indexName + indexPermissions = + allowedVectorStoreIndex.indexPermissions.map { it.toMutableList() } + additionalProperties = allowedVectorStoreIndex.additionalProperties.toMutableMap() + } + + fun indexName(indexName: String) = indexName(JsonField.of(indexName)) + + /** + * Sets [Builder.indexName] to an arbitrary JSON value. + * + * You should usually call [Builder.indexName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun indexName(indexName: JsonField) = apply { this.indexName = indexName } + + fun indexPermissions(indexPermissions: List) = + indexPermissions(JsonField.of(indexPermissions)) + + /** + * Sets [Builder.indexPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.indexPermissions] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun indexPermissions(indexPermissions: JsonField>) = apply { + this.indexPermissions = indexPermissions.map { it.toMutableList() } + } + + /** + * Adds a single [IndexPermission] to [indexPermissions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addIndexPermission(indexPermission: IndexPermission) = apply { + indexPermissions = + (indexPermissions ?: JsonField.of(mutableListOf())).also { + checkKnown("indexPermissions", it).add(indexPermission) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AllowedVectorStoreIndex]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .indexName() + * .indexPermissions() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AllowedVectorStoreIndex = + AllowedVectorStoreIndex( + checkRequired("indexName", indexName), + checkRequired("indexPermissions", indexPermissions).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AllowedVectorStoreIndex = apply { + if (validated) { + return@apply + } + + indexName() + indexPermissions().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (indexName.asKnown().isPresent) 1 else 0) + + (indexPermissions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + class IndexPermission + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val READ = of("read") + + @JvmField val WRITE = of("write") + + @JvmStatic fun of(value: String) = IndexPermission(JsonField.of(value)) + } + + /** An enum containing [IndexPermission]'s known values. */ + enum class Known { + READ, + WRITE, + } + + /** + * An enum containing [IndexPermission]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [IndexPermission] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + READ, + WRITE, + /** + * An enum member indicating that [IndexPermission] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + READ -> Value.READ + WRITE -> Value.WRITE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + READ -> Known.READ + WRITE -> Known.WRITE + else -> throw HanzoInvalidDataException("Unknown IndexPermission: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + HanzoInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): IndexPermission = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is IndexPermission && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AllowedVectorStoreIndex && + indexName == other.indexName && + indexPermissions == other.indexPermissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(indexName, indexPermissions, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AllowedVectorStoreIndex{indexName=$indexName, indexPermissions=$indexPermissions, additionalProperties=$additionalProperties}" + } + + class Config + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Config]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Config]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(config: Config) = apply { + additionalProperties = config.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Config]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Config = Config(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Config = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Config && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Config{additionalProperties=$additionalProperties}" + } + + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + class ModelMaxBudget + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelMaxBudget]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelMaxBudget]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelMaxBudget: ModelMaxBudget) = apply { + additionalProperties = modelMaxBudget.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelMaxBudget]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelMaxBudget = ModelMaxBudget(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelMaxBudget = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelMaxBudget && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelMaxBudget{additionalProperties=$additionalProperties}" + } + + class ModelRpmLimit + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelRpmLimit]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelRpmLimit]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelRpmLimit: ModelRpmLimit) = apply { + additionalProperties = modelRpmLimit.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelRpmLimit]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelRpmLimit = ModelRpmLimit(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelRpmLimit = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelRpmLimit && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelRpmLimit{additionalProperties=$additionalProperties}" + } + + class ModelTpmLimit + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelTpmLimit]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelTpmLimit]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelTpmLimit: ModelTpmLimit) = apply { + additionalProperties = modelTpmLimit.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelTpmLimit]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelTpmLimit = ModelTpmLimit(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelTpmLimit = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelTpmLimit && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelTpmLimit{additionalProperties=$additionalProperties}" + } + + class ObjectPermission + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val agentAccessGroups: JsonField>, + private val agents: JsonField>, + private val mcpAccessGroups: JsonField>, + private val mcpServers: JsonField>, + private val mcpToolPermissions: JsonField, + private val vectorStores: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("agent_access_groups") + @ExcludeMissing + agentAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("agents") + @ExcludeMissing + agents: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_access_groups") + @ExcludeMissing + mcpAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_servers") + @ExcludeMissing + mcpServers: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + mcpToolPermissions: JsonField = JsonMissing.of(), + @JsonProperty("vector_stores") + @ExcludeMissing + vectorStores: JsonField> = JsonMissing.of(), + ) : this( + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun agentAccessGroups(): Optional> = + agentAccessGroups.getOptional("agent_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun agents(): Optional> = agents.getOptional("agents") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpAccessGroups(): Optional> = + mcpAccessGroups.getOptional("mcp_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpServers(): Optional> = mcpServers.getOptional("mcp_servers") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpToolPermissions(): Optional = + mcpToolPermissions.getOptional("mcp_tool_permissions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun vectorStores(): Optional> = vectorStores.getOptional("vector_stores") + + /** + * Returns the raw JSON value of [agentAccessGroups]. + * + * Unlike [agentAccessGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("agent_access_groups") + @ExcludeMissing + fun _agentAccessGroups(): JsonField> = agentAccessGroups + + /** + * Returns the raw JSON value of [agents]. + * + * Unlike [agents], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("agents") @ExcludeMissing fun _agents(): JsonField> = agents + + /** + * Returns the raw JSON value of [mcpAccessGroups]. + * + * Unlike [mcpAccessGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("mcp_access_groups") + @ExcludeMissing + fun _mcpAccessGroups(): JsonField> = mcpAccessGroups + + /** + * Returns the raw JSON value of [mcpServers]. + * + * Unlike [mcpServers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("mcp_servers") + @ExcludeMissing + fun _mcpServers(): JsonField> = mcpServers + + /** + * Returns the raw JSON value of [mcpToolPermissions]. + * + * Unlike [mcpToolPermissions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + fun _mcpToolPermissions(): JsonField = mcpToolPermissions + + /** + * Returns the raw JSON value of [vectorStores]. + * + * Unlike [vectorStores], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("vector_stores") + @ExcludeMissing + fun _vectorStores(): JsonField> = vectorStores + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ObjectPermission]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ObjectPermission]. */ + class Builder internal constructor() { + + private var agentAccessGroups: JsonField>? = null + private var agents: JsonField>? = null + private var mcpAccessGroups: JsonField>? = null + private var mcpServers: JsonField>? = null + private var mcpToolPermissions: JsonField = JsonMissing.of() + private var vectorStores: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(objectPermission: ObjectPermission) = apply { + agentAccessGroups = objectPermission.agentAccessGroups.map { it.toMutableList() } + agents = objectPermission.agents.map { it.toMutableList() } + mcpAccessGroups = objectPermission.mcpAccessGroups.map { it.toMutableList() } + mcpServers = objectPermission.mcpServers.map { it.toMutableList() } + mcpToolPermissions = objectPermission.mcpToolPermissions + vectorStores = objectPermission.vectorStores.map { it.toMutableList() } + additionalProperties = objectPermission.additionalProperties.toMutableMap() + } + + fun agentAccessGroups(agentAccessGroups: List?) = + agentAccessGroups(JsonField.ofNullable(agentAccessGroups)) + + /** + * Alias for calling [Builder.agentAccessGroups] with `agentAccessGroups.orElse(null)`. + */ + fun agentAccessGroups(agentAccessGroups: Optional>) = + agentAccessGroups(agentAccessGroups.getOrNull()) + + /** + * Sets [Builder.agentAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.agentAccessGroups] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun agentAccessGroups(agentAccessGroups: JsonField>) = apply { + this.agentAccessGroups = agentAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agentAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgentAccessGroup(agentAccessGroup: String) = apply { + agentAccessGroups = + (agentAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("agentAccessGroups", it).add(agentAccessGroup) + } + } + + fun agents(agents: List?) = agents(JsonField.ofNullable(agents)) + + /** Alias for calling [Builder.agents] with `agents.orElse(null)`. */ + fun agents(agents: Optional>) = agents(agents.getOrNull()) + + /** + * Sets [Builder.agents] to an arbitrary JSON value. + * + * You should usually call [Builder.agents] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun agents(agents: JsonField>) = apply { + this.agents = agents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgent(agent: String) = apply { + agents = + (agents ?: JsonField.of(mutableListOf())).also { + checkKnown("agents", it).add(agent) + } + } + + fun mcpAccessGroups(mcpAccessGroups: List?) = + mcpAccessGroups(JsonField.ofNullable(mcpAccessGroups)) + + /** Alias for calling [Builder.mcpAccessGroups] with `mcpAccessGroups.orElse(null)`. */ + fun mcpAccessGroups(mcpAccessGroups: Optional>) = + mcpAccessGroups(mcpAccessGroups.getOrNull()) + + /** + * Sets [Builder.mcpAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpAccessGroups] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun mcpAccessGroups(mcpAccessGroups: JsonField>) = apply { + this.mcpAccessGroups = mcpAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpAccessGroup(mcpAccessGroup: String) = apply { + mcpAccessGroups = + (mcpAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpAccessGroups", it).add(mcpAccessGroup) + } + } + + fun mcpServers(mcpServers: List?) = mcpServers(JsonField.ofNullable(mcpServers)) + + /** Alias for calling [Builder.mcpServers] with `mcpServers.orElse(null)`. */ + fun mcpServers(mcpServers: Optional>) = mcpServers(mcpServers.getOrNull()) + + /** + * Sets [Builder.mcpServers] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpServers] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun mcpServers(mcpServers: JsonField>) = apply { + this.mcpServers = mcpServers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpServers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpServer(mcpServer: String) = apply { + mcpServers = + (mcpServers ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpServers", it).add(mcpServer) + } + } + + fun mcpToolPermissions(mcpToolPermissions: McpToolPermissions?) = + mcpToolPermissions(JsonField.ofNullable(mcpToolPermissions)) + + /** + * Alias for calling [Builder.mcpToolPermissions] with + * `mcpToolPermissions.orElse(null)`. + */ + fun mcpToolPermissions(mcpToolPermissions: Optional) = + mcpToolPermissions(mcpToolPermissions.getOrNull()) + + /** + * Sets [Builder.mcpToolPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpToolPermissions] with a well-typed + * [McpToolPermissions] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun mcpToolPermissions(mcpToolPermissions: JsonField) = apply { + this.mcpToolPermissions = mcpToolPermissions + } + + fun vectorStores(vectorStores: List?) = + vectorStores(JsonField.ofNullable(vectorStores)) + + /** Alias for calling [Builder.vectorStores] with `vectorStores.orElse(null)`. */ + fun vectorStores(vectorStores: Optional>) = + vectorStores(vectorStores.getOrNull()) + + /** + * Sets [Builder.vectorStores] to an arbitrary JSON value. + * + * You should usually call [Builder.vectorStores] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun vectorStores(vectorStores: JsonField>) = apply { + this.vectorStores = vectorStores.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [vectorStores]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addVectorStore(vectorStore: String) = apply { + vectorStores = + (vectorStores ?: JsonField.of(mutableListOf())).also { + checkKnown("vectorStores", it).add(vectorStore) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ObjectPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ObjectPermission = + ObjectPermission( + (agentAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (agents ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpServers ?: JsonMissing.of()).map { it.toImmutable() }, + mcpToolPermissions, + (vectorStores ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ObjectPermission = apply { + if (validated) { + return@apply + } + + agentAccessGroups() + agents() + mcpAccessGroups() + mcpServers() + mcpToolPermissions().ifPresent { it.validate() } + vectorStores() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (agentAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (agents.asKnown().getOrNull()?.size ?: 0) + + (mcpAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (mcpServers.asKnown().getOrNull()?.size ?: 0) + + (mcpToolPermissions.asKnown().getOrNull()?.validity() ?: 0) + + (vectorStores.asKnown().getOrNull()?.size ?: 0) + + class McpToolPermissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [McpToolPermissions]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [McpToolPermissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(mcpToolPermissions: McpToolPermissions) = apply { + additionalProperties = mcpToolPermissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [McpToolPermissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): McpToolPermissions = + McpToolPermissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): McpToolPermissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is McpToolPermissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "McpToolPermissions{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ObjectPermission && + agentAccessGroups == other.agentAccessGroups && + agents == other.agents && + mcpAccessGroups == other.mcpAccessGroups && + mcpServers == other.mcpServers && + mcpToolPermissions == other.mcpToolPermissions && + vectorStores == other.vectorStores && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ObjectPermission{agentAccessGroups=$agentAccessGroups, agents=$agents, mcpAccessGroups=$mcpAccessGroups, mcpServers=$mcpServers, mcpToolPermissions=$mcpToolPermissions, vectorStores=$vectorStores, additionalProperties=$additionalProperties}" + } + + class Permissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Permissions]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Permissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(permissions: Permissions) = apply { + additionalProperties = permissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Permissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Permissions = Permissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Permissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Permissions && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Permissions{additionalProperties=$additionalProperties}" + } + + /** Set of params that you can modify via `router.update_settings()`. */ + class RouterSettings + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val allowedFails: JsonField, + private val contextWindowFallbacks: JsonField>, + private val cooldownTime: JsonField, + private val fallbacks: JsonField>, + private val maxRetries: JsonField, + private val modelGroupAlias: JsonField, + private val modelGroupRetryPolicy: JsonField, + private val numRetries: JsonField, + private val retryAfter: JsonField, + private val routingStrategy: JsonField, + private val routingStrategyArgs: JsonField, + private val timeout: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("allowed_fails") + @ExcludeMissing + allowedFails: JsonField = JsonMissing.of(), + @JsonProperty("context_window_fallbacks") + @ExcludeMissing + contextWindowFallbacks: JsonField> = JsonMissing.of(), + @JsonProperty("cooldown_time") + @ExcludeMissing + cooldownTime: JsonField = JsonMissing.of(), + @JsonProperty("fallbacks") + @ExcludeMissing + fallbacks: JsonField> = JsonMissing.of(), + @JsonProperty("max_retries") + @ExcludeMissing + maxRetries: JsonField = JsonMissing.of(), + @JsonProperty("model_group_alias") + @ExcludeMissing + modelGroupAlias: JsonField = JsonMissing.of(), + @JsonProperty("model_group_retry_policy") + @ExcludeMissing + modelGroupRetryPolicy: JsonField = JsonMissing.of(), + @JsonProperty("num_retries") + @ExcludeMissing + numRetries: JsonField = JsonMissing.of(), + @JsonProperty("retry_after") + @ExcludeMissing + retryAfter: JsonField = JsonMissing.of(), + @JsonProperty("routing_strategy") + @ExcludeMissing + routingStrategy: JsonField = JsonMissing.of(), + @JsonProperty("routing_strategy_args") + @ExcludeMissing + routingStrategyArgs: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + ) : this( + allowedFails, + contextWindowFallbacks, + cooldownTime, + fallbacks, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedFails(): Optional = allowedFails.getOptional("allowed_fails") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun contextWindowFallbacks(): Optional> = + contextWindowFallbacks.getOptional("context_window_fallbacks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cooldownTime(): Optional = cooldownTime.getOptional("cooldown_time") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fallbacks(): Optional> = fallbacks.getOptional("fallbacks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxRetries(): Optional = maxRetries.getOptional("max_retries") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelGroupAlias(): Optional = + modelGroupAlias.getOptional("model_group_alias") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelGroupRetryPolicy(): Optional = + modelGroupRetryPolicy.getOptional("model_group_retry_policy") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun numRetries(): Optional = numRetries.getOptional("num_retries") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun retryAfter(): Optional = retryAfter.getOptional("retry_after") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routingStrategy(): Optional = routingStrategy.getOptional("routing_strategy") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routingStrategyArgs(): Optional = + routingStrategyArgs.getOptional("routing_strategy_args") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = timeout.getOptional("timeout") + + /** + * Returns the raw JSON value of [allowedFails]. + * + * Unlike [allowedFails], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("allowed_fails") + @ExcludeMissing + fun _allowedFails(): JsonField = allowedFails + + /** + * Returns the raw JSON value of [contextWindowFallbacks]. + * + * Unlike [contextWindowFallbacks], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("context_window_fallbacks") + @ExcludeMissing + fun _contextWindowFallbacks(): JsonField> = + contextWindowFallbacks + + /** + * Returns the raw JSON value of [cooldownTime]. + * + * Unlike [cooldownTime], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cooldown_time") + @ExcludeMissing + fun _cooldownTime(): JsonField = cooldownTime + + /** + * Returns the raw JSON value of [fallbacks]. + * + * Unlike [fallbacks], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fallbacks") + @ExcludeMissing + fun _fallbacks(): JsonField> = fallbacks + + /** + * Returns the raw JSON value of [maxRetries]. + * + * Unlike [maxRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("max_retries") @ExcludeMissing fun _maxRetries(): JsonField = maxRetries + + /** + * Returns the raw JSON value of [modelGroupAlias]. + * + * Unlike [modelGroupAlias], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("model_group_alias") + @ExcludeMissing + fun _modelGroupAlias(): JsonField = modelGroupAlias + + /** + * Returns the raw JSON value of [modelGroupRetryPolicy]. + * + * Unlike [modelGroupRetryPolicy], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("model_group_retry_policy") + @ExcludeMissing + fun _modelGroupRetryPolicy(): JsonField = modelGroupRetryPolicy + + /** + * Returns the raw JSON value of [numRetries]. + * + * Unlike [numRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("num_retries") @ExcludeMissing fun _numRetries(): JsonField = numRetries + + /** + * Returns the raw JSON value of [retryAfter]. + * + * Unlike [retryAfter], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("retry_after") + @ExcludeMissing + fun _retryAfter(): JsonField = retryAfter + + /** + * Returns the raw JSON value of [routingStrategy]. + * + * Unlike [routingStrategy], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("routing_strategy") + @ExcludeMissing + fun _routingStrategy(): JsonField = routingStrategy + + /** + * Returns the raw JSON value of [routingStrategyArgs]. + * + * Unlike [routingStrategyArgs], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("routing_strategy_args") + @ExcludeMissing + fun _routingStrategyArgs(): JsonField = routingStrategyArgs + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RouterSettings]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RouterSettings]. */ + class Builder internal constructor() { + + private var allowedFails: JsonField = JsonMissing.of() + private var contextWindowFallbacks: JsonField>? = + null + private var cooldownTime: JsonField = JsonMissing.of() + private var fallbacks: JsonField>? = null + private var maxRetries: JsonField = JsonMissing.of() + private var modelGroupAlias: JsonField = JsonMissing.of() + private var modelGroupRetryPolicy: JsonField = JsonMissing.of() + private var numRetries: JsonField = JsonMissing.of() + private var retryAfter: JsonField = JsonMissing.of() + private var routingStrategy: JsonField = JsonMissing.of() + private var routingStrategyArgs: JsonField = JsonMissing.of() + private var timeout: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(routerSettings: RouterSettings) = apply { + allowedFails = routerSettings.allowedFails + contextWindowFallbacks = + routerSettings.contextWindowFallbacks.map { it.toMutableList() } + cooldownTime = routerSettings.cooldownTime + fallbacks = routerSettings.fallbacks.map { it.toMutableList() } + maxRetries = routerSettings.maxRetries + modelGroupAlias = routerSettings.modelGroupAlias + modelGroupRetryPolicy = routerSettings.modelGroupRetryPolicy + numRetries = routerSettings.numRetries + retryAfter = routerSettings.retryAfter + routingStrategy = routerSettings.routingStrategy + routingStrategyArgs = routerSettings.routingStrategyArgs + timeout = routerSettings.timeout + additionalProperties = routerSettings.additionalProperties.toMutableMap() + } + + fun allowedFails(allowedFails: Long?) = allowedFails(JsonField.ofNullable(allowedFails)) + + /** + * Alias for [Builder.allowedFails]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun allowedFails(allowedFails: Long) = allowedFails(allowedFails as Long?) + + /** Alias for calling [Builder.allowedFails] with `allowedFails.orElse(null)`. */ + fun allowedFails(allowedFails: Optional) = allowedFails(allowedFails.getOrNull()) + + /** + * Sets [Builder.allowedFails] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedFails] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun allowedFails(allowedFails: JsonField) = apply { + this.allowedFails = allowedFails + } + + fun contextWindowFallbacks(contextWindowFallbacks: List?) = + contextWindowFallbacks(JsonField.ofNullable(contextWindowFallbacks)) + + /** + * Alias for calling [Builder.contextWindowFallbacks] with + * `contextWindowFallbacks.orElse(null)`. + */ + fun contextWindowFallbacks( + contextWindowFallbacks: Optional> + ) = contextWindowFallbacks(contextWindowFallbacks.getOrNull()) + + /** + * Sets [Builder.contextWindowFallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.contextWindowFallbacks] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun contextWindowFallbacks( + contextWindowFallbacks: JsonField> + ) = apply { + this.contextWindowFallbacks = contextWindowFallbacks.map { it.toMutableList() } + } + + /** + * Adds a single [ContextWindowFallback] to [contextWindowFallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addContextWindowFallback(contextWindowFallback: ContextWindowFallback) = apply { + contextWindowFallbacks = + (contextWindowFallbacks ?: JsonField.of(mutableListOf())).also { + checkKnown("contextWindowFallbacks", it).add(contextWindowFallback) + } + } + + fun cooldownTime(cooldownTime: Double?) = + cooldownTime(JsonField.ofNullable(cooldownTime)) + + /** + * Alias for [Builder.cooldownTime]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cooldownTime(cooldownTime: Double) = cooldownTime(cooldownTime as Double?) + + /** Alias for calling [Builder.cooldownTime] with `cooldownTime.orElse(null)`. */ + fun cooldownTime(cooldownTime: Optional) = + cooldownTime(cooldownTime.getOrNull()) + + /** + * Sets [Builder.cooldownTime] to an arbitrary JSON value. + * + * You should usually call [Builder.cooldownTime] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun cooldownTime(cooldownTime: JsonField) = apply { + this.cooldownTime = cooldownTime + } + + fun fallbacks(fallbacks: List?) = fallbacks(JsonField.ofNullable(fallbacks)) + + /** Alias for calling [Builder.fallbacks] with `fallbacks.orElse(null)`. */ + fun fallbacks(fallbacks: Optional>) = fallbacks(fallbacks.getOrNull()) + + /** + * Sets [Builder.fallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.fallbacks] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fallbacks(fallbacks: JsonField>) = apply { + this.fallbacks = fallbacks.map { it.toMutableList() } + } + + /** + * Adds a single [Fallback] to [fallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFallback(fallback: Fallback) = apply { + fallbacks = + (fallbacks ?: JsonField.of(mutableListOf())).also { + checkKnown("fallbacks", it).add(fallback) + } + } + + fun maxRetries(maxRetries: Long?) = maxRetries(JsonField.ofNullable(maxRetries)) + + /** + * Alias for [Builder.maxRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxRetries(maxRetries: Long) = maxRetries(maxRetries as Long?) + + /** Alias for calling [Builder.maxRetries] with `maxRetries.orElse(null)`. */ + fun maxRetries(maxRetries: Optional) = maxRetries(maxRetries.getOrNull()) + + /** + * Sets [Builder.maxRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.maxRetries] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxRetries(maxRetries: JsonField) = apply { this.maxRetries = maxRetries } + + fun modelGroupAlias(modelGroupAlias: ModelGroupAlias?) = + modelGroupAlias(JsonField.ofNullable(modelGroupAlias)) + + /** Alias for calling [Builder.modelGroupAlias] with `modelGroupAlias.orElse(null)`. */ + fun modelGroupAlias(modelGroupAlias: Optional) = + modelGroupAlias(modelGroupAlias.getOrNull()) + + /** + * Sets [Builder.modelGroupAlias] to an arbitrary JSON value. + * + * You should usually call [Builder.modelGroupAlias] with a well-typed [ModelGroupAlias] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun modelGroupAlias(modelGroupAlias: JsonField) = apply { + this.modelGroupAlias = modelGroupAlias + } + + fun modelGroupRetryPolicy(modelGroupRetryPolicy: ModelGroupRetryPolicy?) = + modelGroupRetryPolicy(JsonField.ofNullable(modelGroupRetryPolicy)) + + /** + * Alias for calling [Builder.modelGroupRetryPolicy] with + * `modelGroupRetryPolicy.orElse(null)`. + */ + fun modelGroupRetryPolicy(modelGroupRetryPolicy: Optional) = + modelGroupRetryPolicy(modelGroupRetryPolicy.getOrNull()) + + /** + * Sets [Builder.modelGroupRetryPolicy] to an arbitrary JSON value. + * + * You should usually call [Builder.modelGroupRetryPolicy] with a well-typed + * [ModelGroupRetryPolicy] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun modelGroupRetryPolicy(modelGroupRetryPolicy: JsonField) = + apply { + this.modelGroupRetryPolicy = modelGroupRetryPolicy + } + + fun numRetries(numRetries: Long?) = numRetries(JsonField.ofNullable(numRetries)) + + /** + * Alias for [Builder.numRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun numRetries(numRetries: Long) = numRetries(numRetries as Long?) + + /** Alias for calling [Builder.numRetries] with `numRetries.orElse(null)`. */ + fun numRetries(numRetries: Optional) = numRetries(numRetries.getOrNull()) + + /** + * Sets [Builder.numRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.numRetries] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun numRetries(numRetries: JsonField) = apply { this.numRetries = numRetries } + + fun retryAfter(retryAfter: Double?) = retryAfter(JsonField.ofNullable(retryAfter)) + + /** + * Alias for [Builder.retryAfter]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun retryAfter(retryAfter: Double) = retryAfter(retryAfter as Double?) + + /** Alias for calling [Builder.retryAfter] with `retryAfter.orElse(null)`. */ + fun retryAfter(retryAfter: Optional) = retryAfter(retryAfter.getOrNull()) + + /** + * Sets [Builder.retryAfter] to an arbitrary JSON value. + * + * You should usually call [Builder.retryAfter] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun retryAfter(retryAfter: JsonField) = apply { this.retryAfter = retryAfter } + + fun routingStrategy(routingStrategy: String?) = + routingStrategy(JsonField.ofNullable(routingStrategy)) + + /** Alias for calling [Builder.routingStrategy] with `routingStrategy.orElse(null)`. */ + fun routingStrategy(routingStrategy: Optional) = + routingStrategy(routingStrategy.getOrNull()) + + /** + * Sets [Builder.routingStrategy] to an arbitrary JSON value. + * + * You should usually call [Builder.routingStrategy] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun routingStrategy(routingStrategy: JsonField) = apply { + this.routingStrategy = routingStrategy + } + + fun routingStrategyArgs(routingStrategyArgs: RoutingStrategyArgs?) = + routingStrategyArgs(JsonField.ofNullable(routingStrategyArgs)) + + /** + * Alias for calling [Builder.routingStrategyArgs] with + * `routingStrategyArgs.orElse(null)`. + */ + fun routingStrategyArgs(routingStrategyArgs: Optional) = + routingStrategyArgs(routingStrategyArgs.getOrNull()) + + /** + * Sets [Builder.routingStrategyArgs] to an arbitrary JSON value. + * + * You should usually call [Builder.routingStrategyArgs] with a well-typed + * [RoutingStrategyArgs] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun routingStrategyArgs(routingStrategyArgs: JsonField) = apply { + this.routingStrategyArgs = routingStrategyArgs + } + + fun timeout(timeout: Double?) = timeout(JsonField.ofNullable(timeout)) + + /** + * Alias for [Builder.timeout]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun timeout(timeout: Double) = timeout(timeout as Double?) + + /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ + fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RouterSettings]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RouterSettings = + RouterSettings( + allowedFails, + (contextWindowFallbacks ?: JsonMissing.of()).map { it.toImmutable() }, + cooldownTime, + (fallbacks ?: JsonMissing.of()).map { it.toImmutable() }, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): RouterSettings = apply { + if (validated) { + return@apply + } + + allowedFails() + contextWindowFallbacks().ifPresent { it.forEach { it.validate() } } + cooldownTime() + fallbacks().ifPresent { it.forEach { it.validate() } } + maxRetries() + modelGroupAlias().ifPresent { it.validate() } + modelGroupRetryPolicy().ifPresent { it.validate() } + numRetries() + retryAfter() + routingStrategy() + routingStrategyArgs().ifPresent { it.validate() } + timeout() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (allowedFails.asKnown().isPresent) 1 else 0) + + (contextWindowFallbacks.asKnown().getOrNull()?.sumOf { it.validity().toInt() } + ?: 0) + + (if (cooldownTime.asKnown().isPresent) 1 else 0) + + (fallbacks.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (maxRetries.asKnown().isPresent) 1 else 0) + + (modelGroupAlias.asKnown().getOrNull()?.validity() ?: 0) + + (modelGroupRetryPolicy.asKnown().getOrNull()?.validity() ?: 0) + + (if (numRetries.asKnown().isPresent) 1 else 0) + + (if (retryAfter.asKnown().isPresent) 1 else 0) + + (if (routingStrategy.asKnown().isPresent) 1 else 0) + + (routingStrategyArgs.asKnown().getOrNull()?.validity() ?: 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + class ContextWindowFallback + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ContextWindowFallback]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ContextWindowFallback]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(contextWindowFallback: ContextWindowFallback) = apply { + additionalProperties = contextWindowFallback.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ContextWindowFallback]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ContextWindowFallback = + ContextWindowFallback(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ContextWindowFallback = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ContextWindowFallback && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ContextWindowFallback{additionalProperties=$additionalProperties}" + } + + class Fallback + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Fallback]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Fallback]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fallback: Fallback) = apply { + additionalProperties = fallback.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Fallback]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Fallback = Fallback(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Fallback = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Fallback && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Fallback{additionalProperties=$additionalProperties}" + } + + class ModelGroupAlias + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelGroupAlias]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelGroupAlias]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelGroupAlias: ModelGroupAlias) = apply { + additionalProperties = modelGroupAlias.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelGroupAlias]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelGroupAlias = ModelGroupAlias(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelGroupAlias = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelGroupAlias && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelGroupAlias{additionalProperties=$additionalProperties}" + } + + class ModelGroupRetryPolicy + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ModelGroupRetryPolicy]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelGroupRetryPolicy]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelGroupRetryPolicy: ModelGroupRetryPolicy) = apply { + additionalProperties = modelGroupRetryPolicy.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelGroupRetryPolicy]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelGroupRetryPolicy = + ModelGroupRetryPolicy(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelGroupRetryPolicy = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelGroupRetryPolicy && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ModelGroupRetryPolicy{additionalProperties=$additionalProperties}" + } + + class RoutingStrategyArgs + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RoutingStrategyArgs]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoutingStrategyArgs]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(routingStrategyArgs: RoutingStrategyArgs) = apply { + additionalProperties = routingStrategyArgs.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RoutingStrategyArgs]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RoutingStrategyArgs = + RoutingStrategyArgs(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): RoutingStrategyArgs = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RoutingStrategyArgs && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RoutingStrategyArgs{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RouterSettings && + allowedFails == other.allowedFails && + contextWindowFallbacks == other.contextWindowFallbacks && + cooldownTime == other.cooldownTime && + fallbacks == other.fallbacks && + maxRetries == other.maxRetries && + modelGroupAlias == other.modelGroupAlias && + modelGroupRetryPolicy == other.modelGroupRetryPolicy && + numRetries == other.numRetries && + retryAfter == other.retryAfter && + routingStrategy == other.routingStrategy && + routingStrategyArgs == other.routingStrategyArgs && + timeout == other.timeout && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + allowedFails, + contextWindowFallbacks, + cooldownTime, + fallbacks, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RouterSettings{allowedFails=$allowedFails, contextWindowFallbacks=$contextWindowFallbacks, cooldownTime=$cooldownTime, fallbacks=$fallbacks, maxRetries=$maxRetries, modelGroupAlias=$modelGroupAlias, modelGroupRetryPolicy=$modelGroupRetryPolicy, numRetries=$numRetries, retryAfter=$retryAfter, routingStrategy=$routingStrategy, routingStrategyArgs=$routingStrategyArgs, timeout=$timeout, additionalProperties=$additionalProperties}" + } + + class RpmLimitType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GUARANTEED_THROUGHPUT = of("guaranteed_throughput") + + @JvmField val BEST_EFFORT_THROUGHPUT = of("best_effort_throughput") + + @JvmField val DYNAMIC = of("dynamic") + + @JvmStatic fun of(value: String) = RpmLimitType(JsonField.of(value)) + } + + /** An enum containing [RpmLimitType]'s known values. */ + enum class Known { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + } + + /** + * An enum containing [RpmLimitType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [RpmLimitType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + /** + * An enum member indicating that [RpmLimitType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GUARANTEED_THROUGHPUT -> Value.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Value.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Value.DYNAMIC + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + GUARANTEED_THROUGHPUT -> Known.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Known.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Known.DYNAMIC + else -> throw HanzoInvalidDataException("Unknown RpmLimitType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): RpmLimitType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RpmLimitType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class TpmLimitType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GUARANTEED_THROUGHPUT = of("guaranteed_throughput") + + @JvmField val BEST_EFFORT_THROUGHPUT = of("best_effort_throughput") + + @JvmField val DYNAMIC = of("dynamic") + + @JvmStatic fun of(value: String) = TpmLimitType(JsonField.of(value)) + } + + /** An enum containing [TpmLimitType]'s known values. */ + enum class Known { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + } + + /** + * An enum containing [TpmLimitType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [TpmLimitType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + /** + * An enum member indicating that [TpmLimitType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GUARANTEED_THROUGHPUT -> Value.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Value.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Value.DYNAMIC + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + GUARANTEED_THROUGHPUT -> Known.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Known.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Known.DYNAMIC + else -> throw HanzoInvalidDataException("Unknown TpmLimitType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): TpmLimitType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TpmLimitType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() } override fun equals(other: Any?): Boolean { @@ -2053,11 +6584,16 @@ private constructor( return true } - return /* spotless:off */ other is KeyUpdateParams && llmChangedBy == other.llmChangedBy && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is KeyUpdateParams && + litellmChangedBy == other.litellmChangedBy && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(llmChangedBy, body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(litellmChangedBy, body, additionalHeaders, additionalQueryParams) override fun toString() = - "KeyUpdateParams{llmChangedBy=$llmChangedBy, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "KeyUpdateParams{litellmChangedBy=$litellmChangedBy, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyUpdateResponse.kt index 6141b644..ea9b9d46 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/key/KeyUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.key import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class KeyUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -80,17 +82,30 @@ private constructor(private val additionalProperties: MutableMap, private val allowedCacheControls: JsonField>, + private val allowedPassthroughRoutes: JsonField>, + private val allowedRoutes: JsonField>, + private val allowedVectorStoreIndexes: JsonField>, + private val autoRotate: JsonField, private val blocked: JsonField, private val budgetDuration: JsonField, private val budgetId: JsonField, - private val config: JsonValue, + private val config: JsonField, private val duration: JsonField, private val enforcedParams: JsonField>, private val guardrails: JsonField>, private val key: JsonField, private val keyAlias: JsonField, + private val keyType: JsonField, private val maxBudget: JsonField, private val maxParallelRequests: JsonField, - private val metadata: JsonValue, - private val modelMaxBudget: JsonValue, - private val modelRpmLimit: JsonValue, - private val modelTpmLimit: JsonValue, + private val metadata: JsonField, + private val modelMaxBudget: JsonField, + private val modelRpmLimit: JsonField, + private val modelTpmLimit: JsonField, private val models: JsonField>, + private val newKey: JsonField, private val newMasterKey: JsonField, - private val permissions: JsonValue, + private val objectPermission: JsonField, + private val organizationId: JsonField, + private val permissions: JsonField, + private val prompts: JsonField>, + private val rotationInterval: JsonField, + private val routerSettings: JsonField, private val rpmLimit: JsonField, + private val rpmLimitType: JsonField, private val sendInviteEmail: JsonField, private val softBudget: JsonField, private val spend: JsonField, private val tags: JsonField>, private val teamId: JsonField, private val tpmLimit: JsonField, + private val tpmLimitType: JsonField, private val userId: JsonField, private val additionalProperties: MutableMap, ) { @JsonCreator private constructor( - @JsonProperty("aliases") @ExcludeMissing aliases: JsonValue = JsonMissing.of(), + @JsonProperty("aliases") @ExcludeMissing aliases: JsonField = JsonMissing.of(), @JsonProperty("allowed_cache_controls") @ExcludeMissing allowedCacheControls: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_passthrough_routes") + @ExcludeMissing + allowedPassthroughRoutes: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_routes") + @ExcludeMissing + allowedRoutes: JsonField> = JsonMissing.of(), + @JsonProperty("allowed_vector_store_indexes") + @ExcludeMissing + allowedVectorStoreIndexes: JsonField> = JsonMissing.of(), + @JsonProperty("auto_rotate") + @ExcludeMissing + autoRotate: JsonField = JsonMissing.of(), @JsonProperty("blocked") @ExcludeMissing blocked: JsonField = JsonMissing.of(), @JsonProperty("budget_duration") @ExcludeMissing budgetDuration: JsonField = JsonMissing.of(), @JsonProperty("budget_id") @ExcludeMissing budgetId: JsonField = JsonMissing.of(), - @JsonProperty("config") @ExcludeMissing config: JsonValue = JsonMissing.of(), + @JsonProperty("config") @ExcludeMissing config: JsonField = JsonMissing.of(), @JsonProperty("duration") @ExcludeMissing duration: JsonField = JsonMissing.of(), @JsonProperty("enforced_params") @ExcludeMissing @@ -72,28 +100,50 @@ private constructor( guardrails: JsonField> = JsonMissing.of(), @JsonProperty("key") @ExcludeMissing key: JsonField = JsonMissing.of(), @JsonProperty("key_alias") @ExcludeMissing keyAlias: JsonField = JsonMissing.of(), + @JsonProperty("key_type") @ExcludeMissing keyType: JsonField = JsonMissing.of(), @JsonProperty("max_budget") @ExcludeMissing maxBudget: JsonField = JsonMissing.of(), @JsonProperty("max_parallel_requests") @ExcludeMissing maxParallelRequests: JsonField = JsonMissing.of(), - @JsonProperty("metadata") @ExcludeMissing metadata: JsonValue = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), @JsonProperty("model_max_budget") @ExcludeMissing - modelMaxBudget: JsonValue = JsonMissing.of(), + modelMaxBudget: JsonField = JsonMissing.of(), @JsonProperty("model_rpm_limit") @ExcludeMissing - modelRpmLimit: JsonValue = JsonMissing.of(), + modelRpmLimit: JsonField = JsonMissing.of(), @JsonProperty("model_tpm_limit") @ExcludeMissing - modelTpmLimit: JsonValue = JsonMissing.of(), + modelTpmLimit: JsonField = JsonMissing.of(), @JsonProperty("models") @ExcludeMissing models: JsonField> = JsonMissing.of(), + @JsonProperty("new_key") @ExcludeMissing newKey: JsonField = JsonMissing.of(), @JsonProperty("new_master_key") @ExcludeMissing newMasterKey: JsonField = JsonMissing.of(), - @JsonProperty("permissions") @ExcludeMissing permissions: JsonValue = JsonMissing.of(), + @JsonProperty("object_permission") + @ExcludeMissing + objectPermission: JsonField = JsonMissing.of(), + @JsonProperty("organization_id") + @ExcludeMissing + organizationId: JsonField = JsonMissing.of(), + @JsonProperty("permissions") + @ExcludeMissing + permissions: JsonField = JsonMissing.of(), + @JsonProperty("prompts") + @ExcludeMissing + prompts: JsonField> = JsonMissing.of(), + @JsonProperty("rotation_interval") + @ExcludeMissing + rotationInterval: JsonField = JsonMissing.of(), + @JsonProperty("router_settings") + @ExcludeMissing + routerSettings: JsonField = JsonMissing.of(), @JsonProperty("rpm_limit") @ExcludeMissing rpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("rpm_limit_type") + @ExcludeMissing + rpmLimitType: JsonField = JsonMissing.of(), @JsonProperty("send_invite_email") @ExcludeMissing sendInviteEmail: JsonField = JsonMissing.of(), @@ -104,10 +154,17 @@ private constructor( @JsonProperty("tags") @ExcludeMissing tags: JsonField> = JsonMissing.of(), @JsonProperty("team_id") @ExcludeMissing teamId: JsonField = JsonMissing.of(), @JsonProperty("tpm_limit") @ExcludeMissing tpmLimit: JsonField = JsonMissing.of(), + @JsonProperty("tpm_limit_type") + @ExcludeMissing + tpmLimitType: JsonField = JsonMissing.of(), @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), ) : this( aliases, allowedCacheControls, + allowedPassthroughRoutes, + allowedRoutes, + allowedVectorStoreIndexes, + autoRotate, blocked, budgetDuration, budgetId, @@ -117,6 +174,7 @@ private constructor( guardrails, key, keyAlias, + keyType, maxBudget, maxParallelRequests, metadata, @@ -124,167 +182,292 @@ private constructor( modelRpmLimit, modelTpmLimit, models, + newKey, newMasterKey, + objectPermission, + organizationId, permissions, + prompts, + rotationInterval, + routerSettings, rpmLimit, + rpmLimitType, sendInviteEmail, softBudget, spend, tags, teamId, tpmLimit, + tpmLimitType, userId, mutableMapOf(), ) - @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonValue = aliases + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun aliases(): Optional = aliases.getOptional("aliases") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun allowedCacheControls(): Optional> = - Optional.ofNullable(allowedCacheControls.getNullable("allowed_cache_controls")) + allowedCacheControls.getOptional("allowed_cache_controls") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedPassthroughRoutes(): Optional> = + allowedPassthroughRoutes.getOptional("allowed_passthrough_routes") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedRoutes(): Optional> = allowedRoutes.getOptional("allowed_routes") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedVectorStoreIndexes(): Optional> = + allowedVectorStoreIndexes.getOptional("allowed_vector_store_indexes") + + /** + * Whether this key should be automatically rotated + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun autoRotate(): Optional = autoRotate.getOptional("auto_rotate") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun blocked(): Optional = blocked.getOptional("blocked") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun blocked(): Optional = Optional.ofNullable(blocked.getNullable("blocked")) + fun budgetDuration(): Optional = budgetDuration.getOptional("budget_duration") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetDuration(): Optional = - Optional.ofNullable(budgetDuration.getNullable("budget_duration")) + fun budgetId(): Optional = budgetId.getOptional("budget_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetId(): Optional = Optional.ofNullable(budgetId.getNullable("budget_id")) + fun config(): Optional = config.getOptional("config") - @JsonProperty("config") @ExcludeMissing fun _config(): JsonValue = config + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun duration(): Optional = duration.getOptional("duration") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun duration(): Optional = Optional.ofNullable(duration.getNullable("duration")) + fun enforcedParams(): Optional> = enforcedParams.getOptional("enforced_params") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun enforcedParams(): Optional> = - Optional.ofNullable(enforcedParams.getNullable("enforced_params")) + fun guardrails(): Optional> = guardrails.getOptional("guardrails") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun guardrails(): Optional> = - Optional.ofNullable(guardrails.getNullable("guardrails")) + fun key(): Optional = key.getOptional("key") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun key(): Optional = Optional.ofNullable(key.getNullable("key")) + fun keyAlias(): Optional = keyAlias.getOptional("key_alias") /** + * Enum for key types that determine what routes a key can access + * * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun keyAlias(): Optional = Optional.ofNullable(keyAlias.getNullable("key_alias")) + fun keyType(): Optional = keyType.getOptional("key_type") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun maxBudget(): Optional = Optional.ofNullable(maxBudget.getNullable("max_budget")) + fun maxBudget(): Optional = maxBudget.getOptional("max_budget") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ fun maxParallelRequests(): Optional = - Optional.ofNullable(maxParallelRequests.getNullable("max_parallel_requests")) + maxParallelRequests.getOptional("max_parallel_requests") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelMaxBudget(): Optional = modelMaxBudget.getOptional("model_max_budget") - @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonValue = metadata + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelRpmLimit(): Optional = modelRpmLimit.getOptional("model_rpm_limit") - @JsonProperty("model_max_budget") - @ExcludeMissing - fun _modelMaxBudget(): JsonValue = modelMaxBudget + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelTpmLimit(): Optional = modelTpmLimit.getOptional("model_tpm_limit") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun models(): Optional> = models.getOptional("models") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun newKey(): Optional = newKey.getOptional("new_key") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun newMasterKey(): Optional = newMasterKey.getOptional("new_master_key") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun objectPermission(): Optional = + objectPermission.getOptional("object_permission") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun organizationId(): Optional = organizationId.getOptional("organization_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun permissions(): Optional = permissions.getOptional("permissions") - @JsonProperty("model_rpm_limit") @ExcludeMissing fun _modelRpmLimit(): JsonValue = modelRpmLimit + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun prompts(): Optional> = prompts.getOptional("prompts") - @JsonProperty("model_tpm_limit") @ExcludeMissing fun _modelTpmLimit(): JsonValue = modelTpmLimit + /** + * How often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True + * + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rotationInterval(): Optional = rotationInterval.getOptional("rotation_interval") /** + * Set of params that you can modify via `router.update_settings()`. + * * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun models(): Optional> = Optional.ofNullable(models.getNullable("models")) + fun routerSettings(): Optional = routerSettings.getOptional("router_settings") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun newMasterKey(): Optional = - Optional.ofNullable(newMasterKey.getNullable("new_master_key")) + fun rpmLimit(): Optional = rpmLimit.getOptional("rpm_limit") - @JsonProperty("permissions") @ExcludeMissing fun _permissions(): JsonValue = permissions + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rpmLimitType(): Optional = rpmLimitType.getOptional("rpm_limit_type") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rpmLimit(): Optional = Optional.ofNullable(rpmLimit.getNullable("rpm_limit")) + fun sendInviteEmail(): Optional = sendInviteEmail.getOptional("send_invite_email") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun sendInviteEmail(): Optional = - Optional.ofNullable(sendInviteEmail.getNullable("send_invite_email")) + fun softBudget(): Optional = softBudget.getOptional("soft_budget") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun softBudget(): Optional = Optional.ofNullable(softBudget.getNullable("soft_budget")) + fun spend(): Optional = spend.getOptional("spend") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun spend(): Optional = Optional.ofNullable(spend.getNullable("spend")) + fun tags(): Optional> = tags.getOptional("tags") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tags(): Optional> = Optional.ofNullable(tags.getNullable("tags")) + fun teamId(): Optional = teamId.getOptional("team_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun teamId(): Optional = Optional.ofNullable(teamId.getNullable("team_id")) + fun tpmLimit(): Optional = tpmLimit.getOptional("tpm_limit") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tpmLimit(): Optional = Optional.ofNullable(tpmLimit.getNullable("tpm_limit")) + fun tpmLimitType(): Optional = tpmLimitType.getOptional("tpm_limit_type") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [aliases]. + * + * Unlike [aliases], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("aliases") @ExcludeMissing fun _aliases(): JsonField = aliases /** * Returns the raw JSON value of [allowedCacheControls]. @@ -296,6 +479,43 @@ private constructor( @ExcludeMissing fun _allowedCacheControls(): JsonField> = allowedCacheControls + /** + * Returns the raw JSON value of [allowedPassthroughRoutes]. + * + * Unlike [allowedPassthroughRoutes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("allowed_passthrough_routes") + @ExcludeMissing + fun _allowedPassthroughRoutes(): JsonField> = allowedPassthroughRoutes + + /** + * Returns the raw JSON value of [allowedRoutes]. + * + * Unlike [allowedRoutes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("allowed_routes") + @ExcludeMissing + fun _allowedRoutes(): JsonField> = allowedRoutes + + /** + * Returns the raw JSON value of [allowedVectorStoreIndexes]. + * + * Unlike [allowedVectorStoreIndexes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("allowed_vector_store_indexes") + @ExcludeMissing + fun _allowedVectorStoreIndexes(): JsonField> = + allowedVectorStoreIndexes + + /** + * Returns the raw JSON value of [autoRotate]. + * + * Unlike [autoRotate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("auto_rotate") @ExcludeMissing fun _autoRotate(): JsonField = autoRotate + /** * Returns the raw JSON value of [blocked]. * @@ -319,6 +539,13 @@ private constructor( */ @JsonProperty("budget_id") @ExcludeMissing fun _budgetId(): JsonField = budgetId + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config") @ExcludeMissing fun _config(): JsonField = config + /** * Returns the raw JSON value of [duration]. * @@ -358,6 +585,13 @@ private constructor( */ @JsonProperty("key_alias") @ExcludeMissing fun _keyAlias(): JsonField = keyAlias + /** + * Returns the raw JSON value of [keyType]. + * + * Unlike [keyType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("key_type") @ExcludeMissing fun _keyType(): JsonField = keyType + /** * Returns the raw JSON value of [maxBudget]. * @@ -375,6 +609,40 @@ private constructor( @ExcludeMissing fun _maxParallelRequests(): JsonField = maxParallelRequests + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [modelMaxBudget]. + * + * Unlike [modelMaxBudget], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model_max_budget") + @ExcludeMissing + fun _modelMaxBudget(): JsonField = modelMaxBudget + + /** + * Returns the raw JSON value of [modelRpmLimit]. + * + * Unlike [modelRpmLimit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model_rpm_limit") + @ExcludeMissing + fun _modelRpmLimit(): JsonField = modelRpmLimit + + /** + * Returns the raw JSON value of [modelTpmLimit]. + * + * Unlike [modelTpmLimit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model_tpm_limit") + @ExcludeMissing + fun _modelTpmLimit(): JsonField = modelTpmLimit + /** * Returns the raw JSON value of [models]. * @@ -382,6 +650,13 @@ private constructor( */ @JsonProperty("models") @ExcludeMissing fun _models(): JsonField> = models + /** + * Returns the raw JSON value of [newKey]. + * + * Unlike [newKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("new_key") @ExcludeMissing fun _newKey(): JsonField = newKey + /** * Returns the raw JSON value of [newMasterKey]. * @@ -391,6 +666,60 @@ private constructor( @ExcludeMissing fun _newMasterKey(): JsonField = newMasterKey + /** + * Returns the raw JSON value of [objectPermission]. + * + * Unlike [objectPermission], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("object_permission") + @ExcludeMissing + fun _objectPermission(): JsonField = objectPermission + + /** + * Returns the raw JSON value of [organizationId]. + * + * Unlike [organizationId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("organization_id") + @ExcludeMissing + fun _organizationId(): JsonField = organizationId + + /** + * Returns the raw JSON value of [permissions]. + * + * Unlike [permissions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permissions") + @ExcludeMissing + fun _permissions(): JsonField = permissions + + /** + * Returns the raw JSON value of [prompts]. + * + * Unlike [prompts], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prompts") @ExcludeMissing fun _prompts(): JsonField> = prompts + + /** + * Returns the raw JSON value of [rotationInterval]. + * + * Unlike [rotationInterval], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("rotation_interval") + @ExcludeMissing + fun _rotationInterval(): JsonField = rotationInterval + + /** + * Returns the raw JSON value of [routerSettings]. + * + * Unlike [routerSettings], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("router_settings") + @ExcludeMissing + fun _routerSettings(): JsonField = routerSettings + /** * Returns the raw JSON value of [rpmLimit]. * @@ -398,6 +727,15 @@ private constructor( */ @JsonProperty("rpm_limit") @ExcludeMissing fun _rpmLimit(): JsonField = rpmLimit + /** + * Returns the raw JSON value of [rpmLimitType]. + * + * Unlike [rpmLimitType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("rpm_limit_type") + @ExcludeMissing + fun _rpmLimitType(): JsonField = rpmLimitType + /** * Returns the raw JSON value of [sendInviteEmail]. * @@ -442,6 +780,15 @@ private constructor( */ @JsonProperty("tpm_limit") @ExcludeMissing fun _tpmLimit(): JsonField = tpmLimit + /** + * Returns the raw JSON value of [tpmLimitType]. + * + * Unlike [tpmLimitType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tpm_limit_type") + @ExcludeMissing + fun _tpmLimitType(): JsonField = tpmLimitType + /** * Returns the raw JSON value of [userId]. * @@ -470,33 +817,47 @@ private constructor( /** A builder for [RegenerateKeyRequest]. */ class Builder internal constructor() { - private var aliases: JsonValue = JsonMissing.of() + private var aliases: JsonField = JsonMissing.of() private var allowedCacheControls: JsonField>? = null + private var allowedPassthroughRoutes: JsonField>? = null + private var allowedRoutes: JsonField>? = null + private var allowedVectorStoreIndexes: JsonField>? = + null + private var autoRotate: JsonField = JsonMissing.of() private var blocked: JsonField = JsonMissing.of() private var budgetDuration: JsonField = JsonMissing.of() private var budgetId: JsonField = JsonMissing.of() - private var config: JsonValue = JsonMissing.of() + private var config: JsonField = JsonMissing.of() private var duration: JsonField = JsonMissing.of() private var enforcedParams: JsonField>? = null private var guardrails: JsonField>? = null private var key: JsonField = JsonMissing.of() private var keyAlias: JsonField = JsonMissing.of() + private var keyType: JsonField = JsonMissing.of() private var maxBudget: JsonField = JsonMissing.of() private var maxParallelRequests: JsonField = JsonMissing.of() - private var metadata: JsonValue = JsonMissing.of() - private var modelMaxBudget: JsonValue = JsonMissing.of() - private var modelRpmLimit: JsonValue = JsonMissing.of() - private var modelTpmLimit: JsonValue = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var modelMaxBudget: JsonField = JsonMissing.of() + private var modelRpmLimit: JsonField = JsonMissing.of() + private var modelTpmLimit: JsonField = JsonMissing.of() private var models: JsonField>? = null + private var newKey: JsonField = JsonMissing.of() private var newMasterKey: JsonField = JsonMissing.of() - private var permissions: JsonValue = JsonMissing.of() + private var objectPermission: JsonField = JsonMissing.of() + private var organizationId: JsonField = JsonMissing.of() + private var permissions: JsonField = JsonMissing.of() + private var prompts: JsonField>? = null + private var rotationInterval: JsonField = JsonMissing.of() + private var routerSettings: JsonField = JsonMissing.of() private var rpmLimit: JsonField = JsonMissing.of() + private var rpmLimitType: JsonField = JsonMissing.of() private var sendInviteEmail: JsonField = JsonMissing.of() private var softBudget: JsonField = JsonMissing.of() private var spend: JsonField = JsonMissing.of() private var tags: JsonField>? = null private var teamId: JsonField = JsonMissing.of() private var tpmLimit: JsonField = JsonMissing.of() + private var tpmLimitType: JsonField = JsonMissing.of() private var userId: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @@ -505,6 +866,12 @@ private constructor( aliases = regenerateKeyRequest.aliases allowedCacheControls = regenerateKeyRequest.allowedCacheControls.map { it.toMutableList() } + allowedPassthroughRoutes = + regenerateKeyRequest.allowedPassthroughRoutes.map { it.toMutableList() } + allowedRoutes = regenerateKeyRequest.allowedRoutes.map { it.toMutableList() } + allowedVectorStoreIndexes = + regenerateKeyRequest.allowedVectorStoreIndexes.map { it.toMutableList() } + autoRotate = regenerateKeyRequest.autoRotate blocked = regenerateKeyRequest.blocked budgetDuration = regenerateKeyRequest.budgetDuration budgetId = regenerateKeyRequest.budgetId @@ -514,6 +881,7 @@ private constructor( guardrails = regenerateKeyRequest.guardrails.map { it.toMutableList() } key = regenerateKeyRequest.key keyAlias = regenerateKeyRequest.keyAlias + keyType = regenerateKeyRequest.keyType maxBudget = regenerateKeyRequest.maxBudget maxParallelRequests = regenerateKeyRequest.maxParallelRequests metadata = regenerateKeyRequest.metadata @@ -521,20 +889,39 @@ private constructor( modelRpmLimit = regenerateKeyRequest.modelRpmLimit modelTpmLimit = regenerateKeyRequest.modelTpmLimit models = regenerateKeyRequest.models.map { it.toMutableList() } + newKey = regenerateKeyRequest.newKey newMasterKey = regenerateKeyRequest.newMasterKey + objectPermission = regenerateKeyRequest.objectPermission + organizationId = regenerateKeyRequest.organizationId permissions = regenerateKeyRequest.permissions + prompts = regenerateKeyRequest.prompts.map { it.toMutableList() } + rotationInterval = regenerateKeyRequest.rotationInterval + routerSettings = regenerateKeyRequest.routerSettings rpmLimit = regenerateKeyRequest.rpmLimit + rpmLimitType = regenerateKeyRequest.rpmLimitType sendInviteEmail = regenerateKeyRequest.sendInviteEmail softBudget = regenerateKeyRequest.softBudget spend = regenerateKeyRequest.spend tags = regenerateKeyRequest.tags.map { it.toMutableList() } teamId = regenerateKeyRequest.teamId tpmLimit = regenerateKeyRequest.tpmLimit + tpmLimitType = regenerateKeyRequest.tpmLimitType userId = regenerateKeyRequest.userId additionalProperties = regenerateKeyRequest.additionalProperties.toMutableMap() } - fun aliases(aliases: JsonValue) = apply { this.aliases = aliases } + fun aliases(aliases: Aliases?) = aliases(JsonField.ofNullable(aliases)) + + /** Alias for calling [Builder.aliases] with `aliases.orElse(null)`. */ + fun aliases(aliases: Optional) = aliases(aliases.getOrNull()) + + /** + * Sets [Builder.aliases] to an arbitrary JSON value. + * + * You should usually call [Builder.aliases] with a well-typed [Aliases] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun aliases(aliases: JsonField) = apply { this.aliases = aliases } fun allowedCacheControls(allowedCacheControls: List?) = allowedCacheControls(JsonField.ofNullable(allowedCacheControls)) @@ -569,60 +956,192 @@ private constructor( } } - fun blocked(blocked: Boolean?) = blocked(JsonField.ofNullable(blocked)) + fun allowedPassthroughRoutes(allowedPassthroughRoutes: List?) = + allowedPassthroughRoutes(JsonField.ofNullable(allowedPassthroughRoutes)) /** - * Alias for [Builder.blocked]. - * - * This unboxed primitive overload exists for backwards compatibility. + * Alias for calling [Builder.allowedPassthroughRoutes] with + * `allowedPassthroughRoutes.orElse(null)`. */ - fun blocked(blocked: Boolean) = blocked(blocked as Boolean?) + fun allowedPassthroughRoutes(allowedPassthroughRoutes: Optional>) = + allowedPassthroughRoutes(allowedPassthroughRoutes.getOrNull()) - /** Alias for calling [Builder.blocked] with `blocked.orElse(null)`. */ - fun blocked(blocked: Optional) = blocked(blocked.getOrNull()) + /** + * Sets [Builder.allowedPassthroughRoutes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedPassthroughRoutes] with a well-typed + * `List` value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun allowedPassthroughRoutes(allowedPassthroughRoutes: JsonField>) = apply { + this.allowedPassthroughRoutes = allowedPassthroughRoutes.map { it.toMutableList() } + } /** - * Sets [Builder.blocked] to an arbitrary JSON value. + * Adds a single [JsonValue] to [allowedPassthroughRoutes]. * - * You should usually call [Builder.blocked] with a well-typed [Boolean] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws IllegalStateException if the field was previously set to a non-list. */ - fun blocked(blocked: JsonField) = apply { this.blocked = blocked } + fun addAllowedPassthroughRoute(allowedPassthroughRoute: JsonValue) = apply { + allowedPassthroughRoutes = + (allowedPassthroughRoutes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedPassthroughRoutes", it).add(allowedPassthroughRoute) + } + } - fun budgetDuration(budgetDuration: String?) = - budgetDuration(JsonField.ofNullable(budgetDuration)) + fun allowedRoutes(allowedRoutes: List?) = + allowedRoutes(JsonField.ofNullable(allowedRoutes)) - /** Alias for calling [Builder.budgetDuration] with `budgetDuration.orElse(null)`. */ - fun budgetDuration(budgetDuration: Optional) = - budgetDuration(budgetDuration.getOrNull()) + /** Alias for calling [Builder.allowedRoutes] with `allowedRoutes.orElse(null)`. */ + fun allowedRoutes(allowedRoutes: Optional>) = + allowedRoutes(allowedRoutes.getOrNull()) /** - * Sets [Builder.budgetDuration] to an arbitrary JSON value. + * Sets [Builder.allowedRoutes] to an arbitrary JSON value. * - * You should usually call [Builder.budgetDuration] with a well-typed [String] value + * You should usually call [Builder.allowedRoutes] with a well-typed `List` value * instead. This method is primarily for setting the field to an undocumented or not yet * supported value. */ - fun budgetDuration(budgetDuration: JsonField) = apply { - this.budgetDuration = budgetDuration + fun allowedRoutes(allowedRoutes: JsonField>) = apply { + this.allowedRoutes = allowedRoutes.map { it.toMutableList() } } - fun budgetId(budgetId: String?) = budgetId(JsonField.ofNullable(budgetId)) - - /** Alias for calling [Builder.budgetId] with `budgetId.orElse(null)`. */ - fun budgetId(budgetId: Optional) = budgetId(budgetId.getOrNull()) - /** - * Sets [Builder.budgetId] to an arbitrary JSON value. + * Adds a single [JsonValue] to [allowedRoutes]. * - * You should usually call [Builder.budgetId] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. + * @throws IllegalStateException if the field was previously set to a non-list. */ - fun budgetId(budgetId: JsonField) = apply { this.budgetId = budgetId } - - fun config(config: JsonValue) = apply { this.config = config } + fun addAllowedRoute(allowedRoute: JsonValue) = apply { + allowedRoutes = + (allowedRoutes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedRoutes", it).add(allowedRoute) + } + } - fun duration(duration: String?) = duration(JsonField.ofNullable(duration)) + fun allowedVectorStoreIndexes(allowedVectorStoreIndexes: List?) = + allowedVectorStoreIndexes(JsonField.ofNullable(allowedVectorStoreIndexes)) + + /** + * Alias for calling [Builder.allowedVectorStoreIndexes] with + * `allowedVectorStoreIndexes.orElse(null)`. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: Optional> + ) = allowedVectorStoreIndexes(allowedVectorStoreIndexes.getOrNull()) + + /** + * Sets [Builder.allowedVectorStoreIndexes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedVectorStoreIndexes] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun allowedVectorStoreIndexes( + allowedVectorStoreIndexes: JsonField> + ) = apply { + this.allowedVectorStoreIndexes = allowedVectorStoreIndexes.map { it.toMutableList() } + } + + /** + * Adds a single [AllowedVectorStoreIndex] to [allowedVectorStoreIndexes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAllowedVectorStoreIndex(allowedVectorStoreIndex: AllowedVectorStoreIndex) = apply { + allowedVectorStoreIndexes = + (allowedVectorStoreIndexes ?: JsonField.of(mutableListOf())).also { + checkKnown("allowedVectorStoreIndexes", it).add(allowedVectorStoreIndex) + } + } + + /** Whether this key should be automatically rotated */ + fun autoRotate(autoRotate: Boolean?) = autoRotate(JsonField.ofNullable(autoRotate)) + + /** + * Alias for [Builder.autoRotate]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun autoRotate(autoRotate: Boolean) = autoRotate(autoRotate as Boolean?) + + /** Alias for calling [Builder.autoRotate] with `autoRotate.orElse(null)`. */ + fun autoRotate(autoRotate: Optional) = autoRotate(autoRotate.getOrNull()) + + /** + * Sets [Builder.autoRotate] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRotate] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun autoRotate(autoRotate: JsonField) = apply { this.autoRotate = autoRotate } + + fun blocked(blocked: Boolean?) = blocked(JsonField.ofNullable(blocked)) + + /** + * Alias for [Builder.blocked]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun blocked(blocked: Boolean) = blocked(blocked as Boolean?) + + /** Alias for calling [Builder.blocked] with `blocked.orElse(null)`. */ + fun blocked(blocked: Optional) = blocked(blocked.getOrNull()) + + /** + * Sets [Builder.blocked] to an arbitrary JSON value. + * + * You should usually call [Builder.blocked] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun blocked(blocked: JsonField) = apply { this.blocked = blocked } + + fun budgetDuration(budgetDuration: String?) = + budgetDuration(JsonField.ofNullable(budgetDuration)) + + /** Alias for calling [Builder.budgetDuration] with `budgetDuration.orElse(null)`. */ + fun budgetDuration(budgetDuration: Optional) = + budgetDuration(budgetDuration.getOrNull()) + + /** + * Sets [Builder.budgetDuration] to an arbitrary JSON value. + * + * You should usually call [Builder.budgetDuration] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun budgetDuration(budgetDuration: JsonField) = apply { + this.budgetDuration = budgetDuration + } + + fun budgetId(budgetId: String?) = budgetId(JsonField.ofNullable(budgetId)) + + /** Alias for calling [Builder.budgetId] with `budgetId.orElse(null)`. */ + fun budgetId(budgetId: Optional) = budgetId(budgetId.getOrNull()) + + /** + * Sets [Builder.budgetId] to an arbitrary JSON value. + * + * You should usually call [Builder.budgetId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun budgetId(budgetId: JsonField) = apply { this.budgetId = budgetId } + + fun config(config: Config?) = config(JsonField.ofNullable(config)) + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [Config] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun config(config: JsonField) = apply { this.config = config } + + fun duration(duration: String?) = duration(JsonField.ofNullable(duration)) /** Alias for calling [Builder.duration] with `duration.orElse(null)`. */ fun duration(duration: Optional) = duration(duration.getOrNull()) @@ -719,6 +1238,20 @@ private constructor( */ fun keyAlias(keyAlias: JsonField) = apply { this.keyAlias = keyAlias } + /** Enum for key types that determine what routes a key can access */ + fun keyType(keyType: KeyType?) = keyType(JsonField.ofNullable(keyType)) + + /** Alias for calling [Builder.keyType] with `keyType.orElse(null)`. */ + fun keyType(keyType: Optional) = keyType(keyType.getOrNull()) + + /** + * Sets [Builder.keyType] to an arbitrary JSON value. + * + * You should usually call [Builder.keyType] with a well-typed [KeyType] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun keyType(keyType: JsonField) = apply { this.keyType = keyType } + fun maxBudget(maxBudget: Double?) = maxBudget(JsonField.ofNullable(maxBudget)) /** @@ -768,15 +1301,73 @@ private constructor( this.maxParallelRequests = maxParallelRequests } - fun metadata(metadata: JsonValue) = apply { this.metadata = metadata } + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) - fun modelMaxBudget(modelMaxBudget: JsonValue) = apply { + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun modelMaxBudget(modelMaxBudget: ModelMaxBudget?) = + modelMaxBudget(JsonField.ofNullable(modelMaxBudget)) + + /** Alias for calling [Builder.modelMaxBudget] with `modelMaxBudget.orElse(null)`. */ + fun modelMaxBudget(modelMaxBudget: Optional) = + modelMaxBudget(modelMaxBudget.getOrNull()) + + /** + * Sets [Builder.modelMaxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.modelMaxBudget] with a well-typed [ModelMaxBudget] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelMaxBudget(modelMaxBudget: JsonField) = apply { this.modelMaxBudget = modelMaxBudget } - fun modelRpmLimit(modelRpmLimit: JsonValue) = apply { this.modelRpmLimit = modelRpmLimit } + fun modelRpmLimit(modelRpmLimit: ModelRpmLimit?) = + modelRpmLimit(JsonField.ofNullable(modelRpmLimit)) + + /** Alias for calling [Builder.modelRpmLimit] with `modelRpmLimit.orElse(null)`. */ + fun modelRpmLimit(modelRpmLimit: Optional) = + modelRpmLimit(modelRpmLimit.getOrNull()) + + /** + * Sets [Builder.modelRpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.modelRpmLimit] with a well-typed [ModelRpmLimit] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelRpmLimit(modelRpmLimit: JsonField) = apply { + this.modelRpmLimit = modelRpmLimit + } + + fun modelTpmLimit(modelTpmLimit: ModelTpmLimit?) = + modelTpmLimit(JsonField.ofNullable(modelTpmLimit)) - fun modelTpmLimit(modelTpmLimit: JsonValue) = apply { this.modelTpmLimit = modelTpmLimit } + /** Alias for calling [Builder.modelTpmLimit] with `modelTpmLimit.orElse(null)`. */ + fun modelTpmLimit(modelTpmLimit: Optional) = + modelTpmLimit(modelTpmLimit.getOrNull()) + + /** + * Sets [Builder.modelTpmLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.modelTpmLimit] with a well-typed [ModelTpmLimit] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelTpmLimit(modelTpmLimit: JsonField) = apply { + this.modelTpmLimit = modelTpmLimit + } fun models(models: List?) = models(JsonField.ofNullable(models)) @@ -806,6 +1397,19 @@ private constructor( } } + fun newKey(newKey: String?) = newKey(JsonField.ofNullable(newKey)) + + /** Alias for calling [Builder.newKey] with `newKey.orElse(null)`. */ + fun newKey(newKey: Optional) = newKey(newKey.getOrNull()) + + /** + * Sets [Builder.newKey] to an arbitrary JSON value. + * + * You should usually call [Builder.newKey] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun newKey(newKey: JsonField) = apply { this.newKey = newKey } + fun newMasterKey(newMasterKey: String?) = newMasterKey(JsonField.ofNullable(newMasterKey)) /** Alias for calling [Builder.newMasterKey] with `newMasterKey.orElse(null)`. */ @@ -822,7 +1426,123 @@ private constructor( this.newMasterKey = newMasterKey } - fun permissions(permissions: JsonValue) = apply { this.permissions = permissions } + fun objectPermission(objectPermission: ObjectPermission?) = + objectPermission(JsonField.ofNullable(objectPermission)) + + /** Alias for calling [Builder.objectPermission] with `objectPermission.orElse(null)`. */ + fun objectPermission(objectPermission: Optional) = + objectPermission(objectPermission.getOrNull()) + + /** + * Sets [Builder.objectPermission] to an arbitrary JSON value. + * + * You should usually call [Builder.objectPermission] with a well-typed [ObjectPermission] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun objectPermission(objectPermission: JsonField) = apply { + this.objectPermission = objectPermission + } + + fun organizationId(organizationId: String?) = + organizationId(JsonField.ofNullable(organizationId)) + + /** Alias for calling [Builder.organizationId] with `organizationId.orElse(null)`. */ + fun organizationId(organizationId: Optional) = + organizationId(organizationId.getOrNull()) + + /** + * Sets [Builder.organizationId] to an arbitrary JSON value. + * + * You should usually call [Builder.organizationId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun organizationId(organizationId: JsonField) = apply { + this.organizationId = organizationId + } + + fun permissions(permissions: Permissions?) = permissions(JsonField.ofNullable(permissions)) + + /** Alias for calling [Builder.permissions] with `permissions.orElse(null)`. */ + fun permissions(permissions: Optional) = permissions(permissions.getOrNull()) + + /** + * Sets [Builder.permissions] to an arbitrary JSON value. + * + * You should usually call [Builder.permissions] with a well-typed [Permissions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun permissions(permissions: JsonField) = apply { + this.permissions = permissions + } + + fun prompts(prompts: List?) = prompts(JsonField.ofNullable(prompts)) + + /** Alias for calling [Builder.prompts] with `prompts.orElse(null)`. */ + fun prompts(prompts: Optional>) = prompts(prompts.getOrNull()) + + /** + * Sets [Builder.prompts] to an arbitrary JSON value. + * + * You should usually call [Builder.prompts] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun prompts(prompts: JsonField>) = apply { + this.prompts = prompts.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [prompts]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addPrompt(prompt: String) = apply { + prompts = + (prompts ?: JsonField.of(mutableListOf())).also { + checkKnown("prompts", it).add(prompt) + } + } + + /** How often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True */ + fun rotationInterval(rotationInterval: String?) = + rotationInterval(JsonField.ofNullable(rotationInterval)) + + /** Alias for calling [Builder.rotationInterval] with `rotationInterval.orElse(null)`. */ + fun rotationInterval(rotationInterval: Optional) = + rotationInterval(rotationInterval.getOrNull()) + + /** + * Sets [Builder.rotationInterval] to an arbitrary JSON value. + * + * You should usually call [Builder.rotationInterval] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rotationInterval(rotationInterval: JsonField) = apply { + this.rotationInterval = rotationInterval + } + + /** Set of params that you can modify via `router.update_settings()`. */ + fun routerSettings(routerSettings: RouterSettings?) = + routerSettings(JsonField.ofNullable(routerSettings)) + + /** Alias for calling [Builder.routerSettings] with `routerSettings.orElse(null)`. */ + fun routerSettings(routerSettings: Optional) = + routerSettings(routerSettings.getOrNull()) + + /** + * Sets [Builder.routerSettings] to an arbitrary JSON value. + * + * You should usually call [Builder.routerSettings] with a well-typed [RouterSettings] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun routerSettings(routerSettings: JsonField) = apply { + this.routerSettings = routerSettings + } fun rpmLimit(rpmLimit: Long?) = rpmLimit(JsonField.ofNullable(rpmLimit)) @@ -844,6 +1564,24 @@ private constructor( */ fun rpmLimit(rpmLimit: JsonField) = apply { this.rpmLimit = rpmLimit } + fun rpmLimitType(rpmLimitType: RpmLimitType?) = + rpmLimitType(JsonField.ofNullable(rpmLimitType)) + + /** Alias for calling [Builder.rpmLimitType] with `rpmLimitType.orElse(null)`. */ + fun rpmLimitType(rpmLimitType: Optional) = + rpmLimitType(rpmLimitType.getOrNull()) + + /** + * Sets [Builder.rpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.rpmLimitType] with a well-typed [RpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun rpmLimitType(rpmLimitType: JsonField) = apply { + this.rpmLimitType = rpmLimitType + } + fun sendInviteEmail(sendInviteEmail: Boolean?) = sendInviteEmail(JsonField.ofNullable(sendInviteEmail)) @@ -968,6 +1706,24 @@ private constructor( */ fun tpmLimit(tpmLimit: JsonField) = apply { this.tpmLimit = tpmLimit } + fun tpmLimitType(tpmLimitType: TpmLimitType?) = + tpmLimitType(JsonField.ofNullable(tpmLimitType)) + + /** Alias for calling [Builder.tpmLimitType] with `tpmLimitType.orElse(null)`. */ + fun tpmLimitType(tpmLimitType: Optional) = + tpmLimitType(tpmLimitType.getOrNull()) + + /** + * Sets [Builder.tpmLimitType] to an arbitrary JSON value. + * + * You should usually call [Builder.tpmLimitType] with a well-typed [TpmLimitType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tpmLimitType(tpmLimitType: JsonField) = apply { + this.tpmLimitType = tpmLimitType + } + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ @@ -1009,6 +1765,10 @@ private constructor( RegenerateKeyRequest( aliases, (allowedCacheControls ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedPassthroughRoutes ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedRoutes ?: JsonMissing.of()).map { it.toImmutable() }, + (allowedVectorStoreIndexes ?: JsonMissing.of()).map { it.toImmutable() }, + autoRotate, blocked, budgetDuration, budgetId, @@ -1018,6 +1778,7 @@ private constructor( (guardrails ?: JsonMissing.of()).map { it.toImmutable() }, key, keyAlias, + keyType, maxBudget, maxParallelRequests, metadata, @@ -1025,15 +1786,23 @@ private constructor( modelRpmLimit, modelTpmLimit, (models ?: JsonMissing.of()).map { it.toImmutable() }, + newKey, newMasterKey, + objectPermission, + organizationId, permissions, + (prompts ?: JsonMissing.of()).map { it.toImmutable() }, + rotationInterval, + routerSettings, rpmLimit, + rpmLimitType, sendInviteEmail, softBudget, spend, (tags ?: JsonMissing.of()).map { it.toImmutable() }, teamId, tpmLimit, + tpmLimitType, userId, additionalProperties.toMutableMap(), ) @@ -1046,44 +1815,3467 @@ private constructor( return@apply } + aliases().ifPresent { it.validate() } allowedCacheControls() + allowedPassthroughRoutes() + allowedRoutes() + allowedVectorStoreIndexes().ifPresent { it.forEach { it.validate() } } + autoRotate() blocked() budgetDuration() budgetId() + config().ifPresent { it.validate() } duration() enforcedParams() guardrails() key() keyAlias() + keyType().ifPresent { it.validate() } maxBudget() maxParallelRequests() + metadata().ifPresent { it.validate() } + modelMaxBudget().ifPresent { it.validate() } + modelRpmLimit().ifPresent { it.validate() } + modelTpmLimit().ifPresent { it.validate() } models() + newKey() newMasterKey() + objectPermission().ifPresent { it.validate() } + organizationId() + permissions().ifPresent { it.validate() } + prompts() + rotationInterval() + routerSettings().ifPresent { it.validate() } rpmLimit() + rpmLimitType().ifPresent { it.validate() } sendInviteEmail() softBudget() spend() tags() teamId() tpmLimit() + tpmLimitType().ifPresent { it.validate() } userId() validated = true } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (aliases.asKnown().getOrNull()?.validity() ?: 0) + + (allowedCacheControls.asKnown().getOrNull()?.size ?: 0) + + (allowedPassthroughRoutes.asKnown().getOrNull()?.size ?: 0) + + (allowedRoutes.asKnown().getOrNull()?.size ?: 0) + + (allowedVectorStoreIndexes.asKnown().getOrNull()?.sumOf { it.validity().toInt() } + ?: 0) + + (if (autoRotate.asKnown().isPresent) 1 else 0) + + (if (blocked.asKnown().isPresent) 1 else 0) + + (if (budgetDuration.asKnown().isPresent) 1 else 0) + + (if (budgetId.asKnown().isPresent) 1 else 0) + + (config.asKnown().getOrNull()?.validity() ?: 0) + + (if (duration.asKnown().isPresent) 1 else 0) + + (enforcedParams.asKnown().getOrNull()?.size ?: 0) + + (guardrails.asKnown().getOrNull()?.size ?: 0) + + (if (key.asKnown().isPresent) 1 else 0) + + (if (keyAlias.asKnown().isPresent) 1 else 0) + + (keyType.asKnown().getOrNull()?.validity() ?: 0) + + (if (maxBudget.asKnown().isPresent) 1 else 0) + + (if (maxParallelRequests.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (modelMaxBudget.asKnown().getOrNull()?.validity() ?: 0) + + (modelRpmLimit.asKnown().getOrNull()?.validity() ?: 0) + + (modelTpmLimit.asKnown().getOrNull()?.validity() ?: 0) + + (models.asKnown().getOrNull()?.size ?: 0) + + (if (newKey.asKnown().isPresent) 1 else 0) + + (if (newMasterKey.asKnown().isPresent) 1 else 0) + + (objectPermission.asKnown().getOrNull()?.validity() ?: 0) + + (if (organizationId.asKnown().isPresent) 1 else 0) + + (permissions.asKnown().getOrNull()?.validity() ?: 0) + + (prompts.asKnown().getOrNull()?.size ?: 0) + + (if (rotationInterval.asKnown().isPresent) 1 else 0) + + (routerSettings.asKnown().getOrNull()?.validity() ?: 0) + + (if (rpmLimit.asKnown().isPresent) 1 else 0) + + (rpmLimitType.asKnown().getOrNull()?.validity() ?: 0) + + (if (sendInviteEmail.asKnown().isPresent) 1 else 0) + + (if (softBudget.asKnown().isPresent) 1 else 0) + + (if (spend.asKnown().isPresent) 1 else 0) + + (tags.asKnown().getOrNull()?.size ?: 0) + + (if (teamId.asKnown().isPresent) 1 else 0) + + (if (tpmLimit.asKnown().isPresent) 1 else 0) + + (tpmLimitType.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + class Aliases + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Aliases]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Aliases]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aliases: Aliases) = apply { + additionalProperties = aliases.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Aliases]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Aliases = Aliases(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Aliases = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Aliases && additionalProperties == other.additionalProperties } - return /* spotless:off */ other is RegenerateKeyRequest && aliases == other.aliases && allowedCacheControls == other.allowedCacheControls && blocked == other.blocked && budgetDuration == other.budgetDuration && budgetId == other.budgetId && config == other.config && duration == other.duration && enforcedParams == other.enforcedParams && guardrails == other.guardrails && key == other.key && keyAlias == other.keyAlias && maxBudget == other.maxBudget && maxParallelRequests == other.maxParallelRequests && metadata == other.metadata && modelMaxBudget == other.modelMaxBudget && modelRpmLimit == other.modelRpmLimit && modelTpmLimit == other.modelTpmLimit && models == other.models && newMasterKey == other.newMasterKey && permissions == other.permissions && rpmLimit == other.rpmLimit && sendInviteEmail == other.sendInviteEmail && softBudget == other.softBudget && spend == other.spend && tags == other.tags && teamId == other.teamId && tpmLimit == other.tpmLimit && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Aliases{additionalProperties=$additionalProperties}" } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(aliases, allowedCacheControls, blocked, budgetDuration, budgetId, config, duration, enforcedParams, guardrails, key, keyAlias, maxBudget, maxParallelRequests, metadata, modelMaxBudget, modelRpmLimit, modelTpmLimit, models, newMasterKey, permissions, rpmLimit, sendInviteEmail, softBudget, spend, tags, teamId, tpmLimit, userId, additionalProperties) } - /* spotless:on */ + class AllowedVectorStoreIndex + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val indexName: JsonField, + private val indexPermissions: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("index_name") + @ExcludeMissing + indexName: JsonField = JsonMissing.of(), + @JsonProperty("index_permissions") + @ExcludeMissing + indexPermissions: JsonField> = JsonMissing.of(), + ) : this(indexName, indexPermissions, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun indexName(): String = indexName.getRequired("index_name") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun indexPermissions(): List = + indexPermissions.getRequired("index_permissions") + + /** + * Returns the raw JSON value of [indexName]. + * + * Unlike [indexName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("index_name") @ExcludeMissing fun _indexName(): JsonField = indexName + + /** + * Returns the raw JSON value of [indexPermissions]. + * + * Unlike [indexPermissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("index_permissions") + @ExcludeMissing + fun _indexPermissions(): JsonField> = indexPermissions + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AllowedVectorStoreIndex]. + * + * The following fields are required: + * ```java + * .indexName() + * .indexPermissions() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AllowedVectorStoreIndex]. */ + class Builder internal constructor() { + + private var indexName: JsonField? = null + private var indexPermissions: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(allowedVectorStoreIndex: AllowedVectorStoreIndex) = apply { + indexName = allowedVectorStoreIndex.indexName + indexPermissions = + allowedVectorStoreIndex.indexPermissions.map { it.toMutableList() } + additionalProperties = allowedVectorStoreIndex.additionalProperties.toMutableMap() + } + + fun indexName(indexName: String) = indexName(JsonField.of(indexName)) + + /** + * Sets [Builder.indexName] to an arbitrary JSON value. + * + * You should usually call [Builder.indexName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun indexName(indexName: JsonField) = apply { this.indexName = indexName } + + fun indexPermissions(indexPermissions: List) = + indexPermissions(JsonField.of(indexPermissions)) + + /** + * Sets [Builder.indexPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.indexPermissions] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun indexPermissions(indexPermissions: JsonField>) = apply { + this.indexPermissions = indexPermissions.map { it.toMutableList() } + } + + /** + * Adds a single [IndexPermission] to [indexPermissions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addIndexPermission(indexPermission: IndexPermission) = apply { + indexPermissions = + (indexPermissions ?: JsonField.of(mutableListOf())).also { + checkKnown("indexPermissions", it).add(indexPermission) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AllowedVectorStoreIndex]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .indexName() + * .indexPermissions() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AllowedVectorStoreIndex = + AllowedVectorStoreIndex( + checkRequired("indexName", indexName), + checkRequired("indexPermissions", indexPermissions).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AllowedVectorStoreIndex = apply { + if (validated) { + return@apply + } + + indexName() + indexPermissions().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (indexName.asKnown().isPresent) 1 else 0) + + (indexPermissions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + class IndexPermission + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val READ = of("read") + + @JvmField val WRITE = of("write") + + @JvmStatic fun of(value: String) = IndexPermission(JsonField.of(value)) + } + + /** An enum containing [IndexPermission]'s known values. */ + enum class Known { + READ, + WRITE, + } + + /** + * An enum containing [IndexPermission]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [IndexPermission] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + READ, + WRITE, + /** + * An enum member indicating that [IndexPermission] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + READ -> Value.READ + WRITE -> Value.WRITE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + READ -> Known.READ + WRITE -> Known.WRITE + else -> throw HanzoInvalidDataException("Unknown IndexPermission: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + HanzoInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): IndexPermission = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is IndexPermission && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AllowedVectorStoreIndex && + indexName == other.indexName && + indexPermissions == other.indexPermissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(indexName, indexPermissions, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AllowedVectorStoreIndex{indexName=$indexName, indexPermissions=$indexPermissions, additionalProperties=$additionalProperties}" + } + + class Config + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Config]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Config]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(config: Config) = apply { + additionalProperties = config.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Config]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Config = Config(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Config = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Config && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Config{additionalProperties=$additionalProperties}" + } + + /** Enum for key types that determine what routes a key can access */ + class KeyType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LLM_API = of("llm_api") + + @JvmField val MANAGEMENT = of("management") + + @JvmField val READ_ONLY = of("read_only") + + @JvmField val DEFAULT = of("default") + + @JvmStatic fun of(value: String) = KeyType(JsonField.of(value)) + } + + /** An enum containing [KeyType]'s known values. */ + enum class Known { + LLM_API, + MANAGEMENT, + READ_ONLY, + DEFAULT, + } + + /** + * An enum containing [KeyType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [KeyType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LLM_API, + MANAGEMENT, + READ_ONLY, + DEFAULT, + /** An enum member indicating that [KeyType] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + LLM_API -> Value.LLM_API + MANAGEMENT -> Value.MANAGEMENT + READ_ONLY -> Value.READ_ONLY + DEFAULT -> Value.DEFAULT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + LLM_API -> Known.LLM_API + MANAGEMENT -> Known.MANAGEMENT + READ_ONLY -> Known.READ_ONLY + DEFAULT -> Known.DEFAULT + else -> throw HanzoInvalidDataException("Unknown KeyType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): KeyType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is KeyType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + class ModelMaxBudget + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelMaxBudget]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelMaxBudget]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelMaxBudget: ModelMaxBudget) = apply { + additionalProperties = modelMaxBudget.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelMaxBudget]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelMaxBudget = ModelMaxBudget(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelMaxBudget = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelMaxBudget && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelMaxBudget{additionalProperties=$additionalProperties}" + } + + class ModelRpmLimit + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelRpmLimit]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelRpmLimit]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelRpmLimit: ModelRpmLimit) = apply { + additionalProperties = modelRpmLimit.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelRpmLimit]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelRpmLimit = ModelRpmLimit(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelRpmLimit = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelRpmLimit && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelRpmLimit{additionalProperties=$additionalProperties}" + } + + class ModelTpmLimit + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelTpmLimit]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelTpmLimit]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelTpmLimit: ModelTpmLimit) = apply { + additionalProperties = modelTpmLimit.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelTpmLimit]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelTpmLimit = ModelTpmLimit(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelTpmLimit = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelTpmLimit && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelTpmLimit{additionalProperties=$additionalProperties}" + } + + class ObjectPermission + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val agentAccessGroups: JsonField>, + private val agents: JsonField>, + private val mcpAccessGroups: JsonField>, + private val mcpServers: JsonField>, + private val mcpToolPermissions: JsonField, + private val vectorStores: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("agent_access_groups") + @ExcludeMissing + agentAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("agents") + @ExcludeMissing + agents: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_access_groups") + @ExcludeMissing + mcpAccessGroups: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_servers") + @ExcludeMissing + mcpServers: JsonField> = JsonMissing.of(), + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + mcpToolPermissions: JsonField = JsonMissing.of(), + @JsonProperty("vector_stores") + @ExcludeMissing + vectorStores: JsonField> = JsonMissing.of(), + ) : this( + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun agentAccessGroups(): Optional> = + agentAccessGroups.getOptional("agent_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun agents(): Optional> = agents.getOptional("agents") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpAccessGroups(): Optional> = + mcpAccessGroups.getOptional("mcp_access_groups") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpServers(): Optional> = mcpServers.getOptional("mcp_servers") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcpToolPermissions(): Optional = + mcpToolPermissions.getOptional("mcp_tool_permissions") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun vectorStores(): Optional> = vectorStores.getOptional("vector_stores") + + /** + * Returns the raw JSON value of [agentAccessGroups]. + * + * Unlike [agentAccessGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("agent_access_groups") + @ExcludeMissing + fun _agentAccessGroups(): JsonField> = agentAccessGroups + + /** + * Returns the raw JSON value of [agents]. + * + * Unlike [agents], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("agents") @ExcludeMissing fun _agents(): JsonField> = agents + + /** + * Returns the raw JSON value of [mcpAccessGroups]. + * + * Unlike [mcpAccessGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("mcp_access_groups") + @ExcludeMissing + fun _mcpAccessGroups(): JsonField> = mcpAccessGroups + + /** + * Returns the raw JSON value of [mcpServers]. + * + * Unlike [mcpServers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("mcp_servers") + @ExcludeMissing + fun _mcpServers(): JsonField> = mcpServers + + /** + * Returns the raw JSON value of [mcpToolPermissions]. + * + * Unlike [mcpToolPermissions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("mcp_tool_permissions") + @ExcludeMissing + fun _mcpToolPermissions(): JsonField = mcpToolPermissions + + /** + * Returns the raw JSON value of [vectorStores]. + * + * Unlike [vectorStores], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("vector_stores") + @ExcludeMissing + fun _vectorStores(): JsonField> = vectorStores + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ObjectPermission]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ObjectPermission]. */ + class Builder internal constructor() { + + private var agentAccessGroups: JsonField>? = null + private var agents: JsonField>? = null + private var mcpAccessGroups: JsonField>? = null + private var mcpServers: JsonField>? = null + private var mcpToolPermissions: JsonField = JsonMissing.of() + private var vectorStores: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(objectPermission: ObjectPermission) = apply { + agentAccessGroups = objectPermission.agentAccessGroups.map { it.toMutableList() } + agents = objectPermission.agents.map { it.toMutableList() } + mcpAccessGroups = objectPermission.mcpAccessGroups.map { it.toMutableList() } + mcpServers = objectPermission.mcpServers.map { it.toMutableList() } + mcpToolPermissions = objectPermission.mcpToolPermissions + vectorStores = objectPermission.vectorStores.map { it.toMutableList() } + additionalProperties = objectPermission.additionalProperties.toMutableMap() + } + + fun agentAccessGroups(agentAccessGroups: List?) = + agentAccessGroups(JsonField.ofNullable(agentAccessGroups)) + + /** + * Alias for calling [Builder.agentAccessGroups] with `agentAccessGroups.orElse(null)`. + */ + fun agentAccessGroups(agentAccessGroups: Optional>) = + agentAccessGroups(agentAccessGroups.getOrNull()) + + /** + * Sets [Builder.agentAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.agentAccessGroups] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun agentAccessGroups(agentAccessGroups: JsonField>) = apply { + this.agentAccessGroups = agentAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agentAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgentAccessGroup(agentAccessGroup: String) = apply { + agentAccessGroups = + (agentAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("agentAccessGroups", it).add(agentAccessGroup) + } + } + + fun agents(agents: List?) = agents(JsonField.ofNullable(agents)) + + /** Alias for calling [Builder.agents] with `agents.orElse(null)`. */ + fun agents(agents: Optional>) = agents(agents.getOrNull()) + + /** + * Sets [Builder.agents] to an arbitrary JSON value. + * + * You should usually call [Builder.agents] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun agents(agents: JsonField>) = apply { + this.agents = agents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [agents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAgent(agent: String) = apply { + agents = + (agents ?: JsonField.of(mutableListOf())).also { + checkKnown("agents", it).add(agent) + } + } + + fun mcpAccessGroups(mcpAccessGroups: List?) = + mcpAccessGroups(JsonField.ofNullable(mcpAccessGroups)) + + /** Alias for calling [Builder.mcpAccessGroups] with `mcpAccessGroups.orElse(null)`. */ + fun mcpAccessGroups(mcpAccessGroups: Optional>) = + mcpAccessGroups(mcpAccessGroups.getOrNull()) + + /** + * Sets [Builder.mcpAccessGroups] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpAccessGroups] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun mcpAccessGroups(mcpAccessGroups: JsonField>) = apply { + this.mcpAccessGroups = mcpAccessGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpAccessGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpAccessGroup(mcpAccessGroup: String) = apply { + mcpAccessGroups = + (mcpAccessGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpAccessGroups", it).add(mcpAccessGroup) + } + } + + fun mcpServers(mcpServers: List?) = mcpServers(JsonField.ofNullable(mcpServers)) + + /** Alias for calling [Builder.mcpServers] with `mcpServers.orElse(null)`. */ + fun mcpServers(mcpServers: Optional>) = mcpServers(mcpServers.getOrNull()) + + /** + * Sets [Builder.mcpServers] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpServers] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun mcpServers(mcpServers: JsonField>) = apply { + this.mcpServers = mcpServers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [mcpServers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMcpServer(mcpServer: String) = apply { + mcpServers = + (mcpServers ?: JsonField.of(mutableListOf())).also { + checkKnown("mcpServers", it).add(mcpServer) + } + } + + fun mcpToolPermissions(mcpToolPermissions: McpToolPermissions?) = + mcpToolPermissions(JsonField.ofNullable(mcpToolPermissions)) + + /** + * Alias for calling [Builder.mcpToolPermissions] with + * `mcpToolPermissions.orElse(null)`. + */ + fun mcpToolPermissions(mcpToolPermissions: Optional) = + mcpToolPermissions(mcpToolPermissions.getOrNull()) + + /** + * Sets [Builder.mcpToolPermissions] to an arbitrary JSON value. + * + * You should usually call [Builder.mcpToolPermissions] with a well-typed + * [McpToolPermissions] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun mcpToolPermissions(mcpToolPermissions: JsonField) = apply { + this.mcpToolPermissions = mcpToolPermissions + } + + fun vectorStores(vectorStores: List?) = + vectorStores(JsonField.ofNullable(vectorStores)) + + /** Alias for calling [Builder.vectorStores] with `vectorStores.orElse(null)`. */ + fun vectorStores(vectorStores: Optional>) = + vectorStores(vectorStores.getOrNull()) + + /** + * Sets [Builder.vectorStores] to an arbitrary JSON value. + * + * You should usually call [Builder.vectorStores] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun vectorStores(vectorStores: JsonField>) = apply { + this.vectorStores = vectorStores.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [vectorStores]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addVectorStore(vectorStore: String) = apply { + vectorStores = + (vectorStores ?: JsonField.of(mutableListOf())).also { + checkKnown("vectorStores", it).add(vectorStore) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ObjectPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ObjectPermission = + ObjectPermission( + (agentAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (agents ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpAccessGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (mcpServers ?: JsonMissing.of()).map { it.toImmutable() }, + mcpToolPermissions, + (vectorStores ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ObjectPermission = apply { + if (validated) { + return@apply + } + + agentAccessGroups() + agents() + mcpAccessGroups() + mcpServers() + mcpToolPermissions().ifPresent { it.validate() } + vectorStores() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (agentAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (agents.asKnown().getOrNull()?.size ?: 0) + + (mcpAccessGroups.asKnown().getOrNull()?.size ?: 0) + + (mcpServers.asKnown().getOrNull()?.size ?: 0) + + (mcpToolPermissions.asKnown().getOrNull()?.validity() ?: 0) + + (vectorStores.asKnown().getOrNull()?.size ?: 0) + + class McpToolPermissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [McpToolPermissions]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [McpToolPermissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(mcpToolPermissions: McpToolPermissions) = apply { + additionalProperties = mcpToolPermissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [McpToolPermissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): McpToolPermissions = + McpToolPermissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): McpToolPermissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is McpToolPermissions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "McpToolPermissions{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ObjectPermission && + agentAccessGroups == other.agentAccessGroups && + agents == other.agents && + mcpAccessGroups == other.mcpAccessGroups && + mcpServers == other.mcpServers && + mcpToolPermissions == other.mcpToolPermissions && + vectorStores == other.vectorStores && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + agentAccessGroups, + agents, + mcpAccessGroups, + mcpServers, + mcpToolPermissions, + vectorStores, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ObjectPermission{agentAccessGroups=$agentAccessGroups, agents=$agents, mcpAccessGroups=$mcpAccessGroups, mcpServers=$mcpServers, mcpToolPermissions=$mcpToolPermissions, vectorStores=$vectorStores, additionalProperties=$additionalProperties}" + } + + class Permissions + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Permissions]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Permissions]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(permissions: Permissions) = apply { + additionalProperties = permissions.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Permissions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Permissions = Permissions(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Permissions = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Permissions && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Permissions{additionalProperties=$additionalProperties}" + } + + /** Set of params that you can modify via `router.update_settings()`. */ + class RouterSettings + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val allowedFails: JsonField, + private val contextWindowFallbacks: JsonField>, + private val cooldownTime: JsonField, + private val fallbacks: JsonField>, + private val maxRetries: JsonField, + private val modelGroupAlias: JsonField, + private val modelGroupRetryPolicy: JsonField, + private val numRetries: JsonField, + private val retryAfter: JsonField, + private val routingStrategy: JsonField, + private val routingStrategyArgs: JsonField, + private val timeout: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("allowed_fails") + @ExcludeMissing + allowedFails: JsonField = JsonMissing.of(), + @JsonProperty("context_window_fallbacks") + @ExcludeMissing + contextWindowFallbacks: JsonField> = JsonMissing.of(), + @JsonProperty("cooldown_time") + @ExcludeMissing + cooldownTime: JsonField = JsonMissing.of(), + @JsonProperty("fallbacks") + @ExcludeMissing + fallbacks: JsonField> = JsonMissing.of(), + @JsonProperty("max_retries") + @ExcludeMissing + maxRetries: JsonField = JsonMissing.of(), + @JsonProperty("model_group_alias") + @ExcludeMissing + modelGroupAlias: JsonField = JsonMissing.of(), + @JsonProperty("model_group_retry_policy") + @ExcludeMissing + modelGroupRetryPolicy: JsonField = JsonMissing.of(), + @JsonProperty("num_retries") + @ExcludeMissing + numRetries: JsonField = JsonMissing.of(), + @JsonProperty("retry_after") + @ExcludeMissing + retryAfter: JsonField = JsonMissing.of(), + @JsonProperty("routing_strategy") + @ExcludeMissing + routingStrategy: JsonField = JsonMissing.of(), + @JsonProperty("routing_strategy_args") + @ExcludeMissing + routingStrategyArgs: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + ) : this( + allowedFails, + contextWindowFallbacks, + cooldownTime, + fallbacks, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun allowedFails(): Optional = allowedFails.getOptional("allowed_fails") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun contextWindowFallbacks(): Optional> = + contextWindowFallbacks.getOptional("context_window_fallbacks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cooldownTime(): Optional = cooldownTime.getOptional("cooldown_time") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fallbacks(): Optional> = fallbacks.getOptional("fallbacks") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxRetries(): Optional = maxRetries.getOptional("max_retries") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelGroupAlias(): Optional = + modelGroupAlias.getOptional("model_group_alias") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun modelGroupRetryPolicy(): Optional = + modelGroupRetryPolicy.getOptional("model_group_retry_policy") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun numRetries(): Optional = numRetries.getOptional("num_retries") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun retryAfter(): Optional = retryAfter.getOptional("retry_after") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routingStrategy(): Optional = routingStrategy.getOptional("routing_strategy") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun routingStrategyArgs(): Optional = + routingStrategyArgs.getOptional("routing_strategy_args") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = timeout.getOptional("timeout") + + /** + * Returns the raw JSON value of [allowedFails]. + * + * Unlike [allowedFails], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("allowed_fails") + @ExcludeMissing + fun _allowedFails(): JsonField = allowedFails + + /** + * Returns the raw JSON value of [contextWindowFallbacks]. + * + * Unlike [contextWindowFallbacks], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("context_window_fallbacks") + @ExcludeMissing + fun _contextWindowFallbacks(): JsonField> = + contextWindowFallbacks + + /** + * Returns the raw JSON value of [cooldownTime]. + * + * Unlike [cooldownTime], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("cooldown_time") + @ExcludeMissing + fun _cooldownTime(): JsonField = cooldownTime + + /** + * Returns the raw JSON value of [fallbacks]. + * + * Unlike [fallbacks], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fallbacks") + @ExcludeMissing + fun _fallbacks(): JsonField> = fallbacks + + /** + * Returns the raw JSON value of [maxRetries]. + * + * Unlike [maxRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("max_retries") @ExcludeMissing fun _maxRetries(): JsonField = maxRetries + + /** + * Returns the raw JSON value of [modelGroupAlias]. + * + * Unlike [modelGroupAlias], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("model_group_alias") + @ExcludeMissing + fun _modelGroupAlias(): JsonField = modelGroupAlias + + /** + * Returns the raw JSON value of [modelGroupRetryPolicy]. + * + * Unlike [modelGroupRetryPolicy], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("model_group_retry_policy") + @ExcludeMissing + fun _modelGroupRetryPolicy(): JsonField = modelGroupRetryPolicy + + /** + * Returns the raw JSON value of [numRetries]. + * + * Unlike [numRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("num_retries") @ExcludeMissing fun _numRetries(): JsonField = numRetries + + /** + * Returns the raw JSON value of [retryAfter]. + * + * Unlike [retryAfter], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("retry_after") + @ExcludeMissing + fun _retryAfter(): JsonField = retryAfter + + /** + * Returns the raw JSON value of [routingStrategy]. + * + * Unlike [routingStrategy], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("routing_strategy") + @ExcludeMissing + fun _routingStrategy(): JsonField = routingStrategy + + /** + * Returns the raw JSON value of [routingStrategyArgs]. + * + * Unlike [routingStrategyArgs], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("routing_strategy_args") + @ExcludeMissing + fun _routingStrategyArgs(): JsonField = routingStrategyArgs + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RouterSettings]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RouterSettings]. */ + class Builder internal constructor() { + + private var allowedFails: JsonField = JsonMissing.of() + private var contextWindowFallbacks: JsonField>? = + null + private var cooldownTime: JsonField = JsonMissing.of() + private var fallbacks: JsonField>? = null + private var maxRetries: JsonField = JsonMissing.of() + private var modelGroupAlias: JsonField = JsonMissing.of() + private var modelGroupRetryPolicy: JsonField = JsonMissing.of() + private var numRetries: JsonField = JsonMissing.of() + private var retryAfter: JsonField = JsonMissing.of() + private var routingStrategy: JsonField = JsonMissing.of() + private var routingStrategyArgs: JsonField = JsonMissing.of() + private var timeout: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(routerSettings: RouterSettings) = apply { + allowedFails = routerSettings.allowedFails + contextWindowFallbacks = + routerSettings.contextWindowFallbacks.map { it.toMutableList() } + cooldownTime = routerSettings.cooldownTime + fallbacks = routerSettings.fallbacks.map { it.toMutableList() } + maxRetries = routerSettings.maxRetries + modelGroupAlias = routerSettings.modelGroupAlias + modelGroupRetryPolicy = routerSettings.modelGroupRetryPolicy + numRetries = routerSettings.numRetries + retryAfter = routerSettings.retryAfter + routingStrategy = routerSettings.routingStrategy + routingStrategyArgs = routerSettings.routingStrategyArgs + timeout = routerSettings.timeout + additionalProperties = routerSettings.additionalProperties.toMutableMap() + } + + fun allowedFails(allowedFails: Long?) = allowedFails(JsonField.ofNullable(allowedFails)) + + /** + * Alias for [Builder.allowedFails]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun allowedFails(allowedFails: Long) = allowedFails(allowedFails as Long?) + + /** Alias for calling [Builder.allowedFails] with `allowedFails.orElse(null)`. */ + fun allowedFails(allowedFails: Optional) = allowedFails(allowedFails.getOrNull()) + + /** + * Sets [Builder.allowedFails] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedFails] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun allowedFails(allowedFails: JsonField) = apply { + this.allowedFails = allowedFails + } + + fun contextWindowFallbacks(contextWindowFallbacks: List?) = + contextWindowFallbacks(JsonField.ofNullable(contextWindowFallbacks)) + + /** + * Alias for calling [Builder.contextWindowFallbacks] with + * `contextWindowFallbacks.orElse(null)`. + */ + fun contextWindowFallbacks( + contextWindowFallbacks: Optional> + ) = contextWindowFallbacks(contextWindowFallbacks.getOrNull()) + + /** + * Sets [Builder.contextWindowFallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.contextWindowFallbacks] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun contextWindowFallbacks( + contextWindowFallbacks: JsonField> + ) = apply { + this.contextWindowFallbacks = contextWindowFallbacks.map { it.toMutableList() } + } + + /** + * Adds a single [ContextWindowFallback] to [contextWindowFallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addContextWindowFallback(contextWindowFallback: ContextWindowFallback) = apply { + contextWindowFallbacks = + (contextWindowFallbacks ?: JsonField.of(mutableListOf())).also { + checkKnown("contextWindowFallbacks", it).add(contextWindowFallback) + } + } + + fun cooldownTime(cooldownTime: Double?) = + cooldownTime(JsonField.ofNullable(cooldownTime)) + + /** + * Alias for [Builder.cooldownTime]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cooldownTime(cooldownTime: Double) = cooldownTime(cooldownTime as Double?) + + /** Alias for calling [Builder.cooldownTime] with `cooldownTime.orElse(null)`. */ + fun cooldownTime(cooldownTime: Optional) = + cooldownTime(cooldownTime.getOrNull()) + + /** + * Sets [Builder.cooldownTime] to an arbitrary JSON value. + * + * You should usually call [Builder.cooldownTime] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun cooldownTime(cooldownTime: JsonField) = apply { + this.cooldownTime = cooldownTime + } + + fun fallbacks(fallbacks: List?) = fallbacks(JsonField.ofNullable(fallbacks)) + + /** Alias for calling [Builder.fallbacks] with `fallbacks.orElse(null)`. */ + fun fallbacks(fallbacks: Optional>) = fallbacks(fallbacks.getOrNull()) + + /** + * Sets [Builder.fallbacks] to an arbitrary JSON value. + * + * You should usually call [Builder.fallbacks] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fallbacks(fallbacks: JsonField>) = apply { + this.fallbacks = fallbacks.map { it.toMutableList() } + } + + /** + * Adds a single [Fallback] to [fallbacks]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFallback(fallback: Fallback) = apply { + fallbacks = + (fallbacks ?: JsonField.of(mutableListOf())).also { + checkKnown("fallbacks", it).add(fallback) + } + } + + fun maxRetries(maxRetries: Long?) = maxRetries(JsonField.ofNullable(maxRetries)) + + /** + * Alias for [Builder.maxRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxRetries(maxRetries: Long) = maxRetries(maxRetries as Long?) + + /** Alias for calling [Builder.maxRetries] with `maxRetries.orElse(null)`. */ + fun maxRetries(maxRetries: Optional) = maxRetries(maxRetries.getOrNull()) + + /** + * Sets [Builder.maxRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.maxRetries] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxRetries(maxRetries: JsonField) = apply { this.maxRetries = maxRetries } + + fun modelGroupAlias(modelGroupAlias: ModelGroupAlias?) = + modelGroupAlias(JsonField.ofNullable(modelGroupAlias)) + + /** Alias for calling [Builder.modelGroupAlias] with `modelGroupAlias.orElse(null)`. */ + fun modelGroupAlias(modelGroupAlias: Optional) = + modelGroupAlias(modelGroupAlias.getOrNull()) + + /** + * Sets [Builder.modelGroupAlias] to an arbitrary JSON value. + * + * You should usually call [Builder.modelGroupAlias] with a well-typed [ModelGroupAlias] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun modelGroupAlias(modelGroupAlias: JsonField) = apply { + this.modelGroupAlias = modelGroupAlias + } + + fun modelGroupRetryPolicy(modelGroupRetryPolicy: ModelGroupRetryPolicy?) = + modelGroupRetryPolicy(JsonField.ofNullable(modelGroupRetryPolicy)) + + /** + * Alias for calling [Builder.modelGroupRetryPolicy] with + * `modelGroupRetryPolicy.orElse(null)`. + */ + fun modelGroupRetryPolicy(modelGroupRetryPolicy: Optional) = + modelGroupRetryPolicy(modelGroupRetryPolicy.getOrNull()) + + /** + * Sets [Builder.modelGroupRetryPolicy] to an arbitrary JSON value. + * + * You should usually call [Builder.modelGroupRetryPolicy] with a well-typed + * [ModelGroupRetryPolicy] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun modelGroupRetryPolicy(modelGroupRetryPolicy: JsonField) = + apply { + this.modelGroupRetryPolicy = modelGroupRetryPolicy + } + + fun numRetries(numRetries: Long?) = numRetries(JsonField.ofNullable(numRetries)) + + /** + * Alias for [Builder.numRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun numRetries(numRetries: Long) = numRetries(numRetries as Long?) + + /** Alias for calling [Builder.numRetries] with `numRetries.orElse(null)`. */ + fun numRetries(numRetries: Optional) = numRetries(numRetries.getOrNull()) + + /** + * Sets [Builder.numRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.numRetries] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun numRetries(numRetries: JsonField) = apply { this.numRetries = numRetries } + + fun retryAfter(retryAfter: Double?) = retryAfter(JsonField.ofNullable(retryAfter)) + + /** + * Alias for [Builder.retryAfter]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun retryAfter(retryAfter: Double) = retryAfter(retryAfter as Double?) + + /** Alias for calling [Builder.retryAfter] with `retryAfter.orElse(null)`. */ + fun retryAfter(retryAfter: Optional) = retryAfter(retryAfter.getOrNull()) + + /** + * Sets [Builder.retryAfter] to an arbitrary JSON value. + * + * You should usually call [Builder.retryAfter] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun retryAfter(retryAfter: JsonField) = apply { this.retryAfter = retryAfter } + + fun routingStrategy(routingStrategy: String?) = + routingStrategy(JsonField.ofNullable(routingStrategy)) + + /** Alias for calling [Builder.routingStrategy] with `routingStrategy.orElse(null)`. */ + fun routingStrategy(routingStrategy: Optional) = + routingStrategy(routingStrategy.getOrNull()) + + /** + * Sets [Builder.routingStrategy] to an arbitrary JSON value. + * + * You should usually call [Builder.routingStrategy] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun routingStrategy(routingStrategy: JsonField) = apply { + this.routingStrategy = routingStrategy + } + + fun routingStrategyArgs(routingStrategyArgs: RoutingStrategyArgs?) = + routingStrategyArgs(JsonField.ofNullable(routingStrategyArgs)) + + /** + * Alias for calling [Builder.routingStrategyArgs] with + * `routingStrategyArgs.orElse(null)`. + */ + fun routingStrategyArgs(routingStrategyArgs: Optional) = + routingStrategyArgs(routingStrategyArgs.getOrNull()) + + /** + * Sets [Builder.routingStrategyArgs] to an arbitrary JSON value. + * + * You should usually call [Builder.routingStrategyArgs] with a well-typed + * [RoutingStrategyArgs] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun routingStrategyArgs(routingStrategyArgs: JsonField) = apply { + this.routingStrategyArgs = routingStrategyArgs + } + + fun timeout(timeout: Double?) = timeout(JsonField.ofNullable(timeout)) + + /** + * Alias for [Builder.timeout]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun timeout(timeout: Double) = timeout(timeout as Double?) + + /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ + fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RouterSettings]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RouterSettings = + RouterSettings( + allowedFails, + (contextWindowFallbacks ?: JsonMissing.of()).map { it.toImmutable() }, + cooldownTime, + (fallbacks ?: JsonMissing.of()).map { it.toImmutable() }, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): RouterSettings = apply { + if (validated) { + return@apply + } + + allowedFails() + contextWindowFallbacks().ifPresent { it.forEach { it.validate() } } + cooldownTime() + fallbacks().ifPresent { it.forEach { it.validate() } } + maxRetries() + modelGroupAlias().ifPresent { it.validate() } + modelGroupRetryPolicy().ifPresent { it.validate() } + numRetries() + retryAfter() + routingStrategy() + routingStrategyArgs().ifPresent { it.validate() } + timeout() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (allowedFails.asKnown().isPresent) 1 else 0) + + (contextWindowFallbacks.asKnown().getOrNull()?.sumOf { it.validity().toInt() } + ?: 0) + + (if (cooldownTime.asKnown().isPresent) 1 else 0) + + (fallbacks.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (maxRetries.asKnown().isPresent) 1 else 0) + + (modelGroupAlias.asKnown().getOrNull()?.validity() ?: 0) + + (modelGroupRetryPolicy.asKnown().getOrNull()?.validity() ?: 0) + + (if (numRetries.asKnown().isPresent) 1 else 0) + + (if (retryAfter.asKnown().isPresent) 1 else 0) + + (if (routingStrategy.asKnown().isPresent) 1 else 0) + + (routingStrategyArgs.asKnown().getOrNull()?.validity() ?: 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + class ContextWindowFallback + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ContextWindowFallback]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ContextWindowFallback]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(contextWindowFallback: ContextWindowFallback) = apply { + additionalProperties = contextWindowFallback.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ContextWindowFallback]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ContextWindowFallback = + ContextWindowFallback(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ContextWindowFallback = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ContextWindowFallback && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ContextWindowFallback{additionalProperties=$additionalProperties}" + } + + class Fallback + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Fallback]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Fallback]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fallback: Fallback) = apply { + additionalProperties = fallback.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Fallback]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Fallback = Fallback(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Fallback = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Fallback && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Fallback{additionalProperties=$additionalProperties}" + } + + class ModelGroupAlias + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ModelGroupAlias]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelGroupAlias]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelGroupAlias: ModelGroupAlias) = apply { + additionalProperties = modelGroupAlias.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelGroupAlias]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelGroupAlias = ModelGroupAlias(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelGroupAlias = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelGroupAlias && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ModelGroupAlias{additionalProperties=$additionalProperties}" + } + + class ModelGroupRetryPolicy + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ModelGroupRetryPolicy]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ModelGroupRetryPolicy]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelGroupRetryPolicy: ModelGroupRetryPolicy) = apply { + additionalProperties = modelGroupRetryPolicy.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ModelGroupRetryPolicy]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ModelGroupRetryPolicy = + ModelGroupRetryPolicy(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ModelGroupRetryPolicy = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelGroupRetryPolicy && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ModelGroupRetryPolicy{additionalProperties=$additionalProperties}" + } + + class RoutingStrategyArgs + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RoutingStrategyArgs]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoutingStrategyArgs]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(routingStrategyArgs: RoutingStrategyArgs) = apply { + additionalProperties = routingStrategyArgs.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RoutingStrategyArgs]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RoutingStrategyArgs = + RoutingStrategyArgs(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): RoutingStrategyArgs = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RoutingStrategyArgs && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RoutingStrategyArgs{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RouterSettings && + allowedFails == other.allowedFails && + contextWindowFallbacks == other.contextWindowFallbacks && + cooldownTime == other.cooldownTime && + fallbacks == other.fallbacks && + maxRetries == other.maxRetries && + modelGroupAlias == other.modelGroupAlias && + modelGroupRetryPolicy == other.modelGroupRetryPolicy && + numRetries == other.numRetries && + retryAfter == other.retryAfter && + routingStrategy == other.routingStrategy && + routingStrategyArgs == other.routingStrategyArgs && + timeout == other.timeout && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + allowedFails, + contextWindowFallbacks, + cooldownTime, + fallbacks, + maxRetries, + modelGroupAlias, + modelGroupRetryPolicy, + numRetries, + retryAfter, + routingStrategy, + routingStrategyArgs, + timeout, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RouterSettings{allowedFails=$allowedFails, contextWindowFallbacks=$contextWindowFallbacks, cooldownTime=$cooldownTime, fallbacks=$fallbacks, maxRetries=$maxRetries, modelGroupAlias=$modelGroupAlias, modelGroupRetryPolicy=$modelGroupRetryPolicy, numRetries=$numRetries, retryAfter=$retryAfter, routingStrategy=$routingStrategy, routingStrategyArgs=$routingStrategyArgs, timeout=$timeout, additionalProperties=$additionalProperties}" + } + + class RpmLimitType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GUARANTEED_THROUGHPUT = of("guaranteed_throughput") + + @JvmField val BEST_EFFORT_THROUGHPUT = of("best_effort_throughput") + + @JvmField val DYNAMIC = of("dynamic") + + @JvmStatic fun of(value: String) = RpmLimitType(JsonField.of(value)) + } + + /** An enum containing [RpmLimitType]'s known values. */ + enum class Known { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + } + + /** + * An enum containing [RpmLimitType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [RpmLimitType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + /** + * An enum member indicating that [RpmLimitType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GUARANTEED_THROUGHPUT -> Value.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Value.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Value.DYNAMIC + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + GUARANTEED_THROUGHPUT -> Known.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Known.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Known.DYNAMIC + else -> throw HanzoInvalidDataException("Unknown RpmLimitType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): RpmLimitType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RpmLimitType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class TpmLimitType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GUARANTEED_THROUGHPUT = of("guaranteed_throughput") + + @JvmField val BEST_EFFORT_THROUGHPUT = of("best_effort_throughput") + + @JvmField val DYNAMIC = of("dynamic") + + @JvmStatic fun of(value: String) = TpmLimitType(JsonField.of(value)) + } + + /** An enum containing [TpmLimitType]'s known values. */ + enum class Known { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + } + + /** + * An enum containing [TpmLimitType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [TpmLimitType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GUARANTEED_THROUGHPUT, + BEST_EFFORT_THROUGHPUT, + DYNAMIC, + /** + * An enum member indicating that [TpmLimitType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GUARANTEED_THROUGHPUT -> Value.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Value.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Value.DYNAMIC + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws HanzoInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + GUARANTEED_THROUGHPUT -> Known.GUARANTEED_THROUGHPUT + BEST_EFFORT_THROUGHPUT -> Known.BEST_EFFORT_THROUGHPUT + DYNAMIC -> Known.DYNAMIC + else -> throw HanzoInvalidDataException("Unknown TpmLimitType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws HanzoInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { HanzoInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): TpmLimitType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TpmLimitType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RegenerateKeyRequest && + aliases == other.aliases && + allowedCacheControls == other.allowedCacheControls && + allowedPassthroughRoutes == other.allowedPassthroughRoutes && + allowedRoutes == other.allowedRoutes && + allowedVectorStoreIndexes == other.allowedVectorStoreIndexes && + autoRotate == other.autoRotate && + blocked == other.blocked && + budgetDuration == other.budgetDuration && + budgetId == other.budgetId && + config == other.config && + duration == other.duration && + enforcedParams == other.enforcedParams && + guardrails == other.guardrails && + key == other.key && + keyAlias == other.keyAlias && + keyType == other.keyType && + maxBudget == other.maxBudget && + maxParallelRequests == other.maxParallelRequests && + metadata == other.metadata && + modelMaxBudget == other.modelMaxBudget && + modelRpmLimit == other.modelRpmLimit && + modelTpmLimit == other.modelTpmLimit && + models == other.models && + newKey == other.newKey && + newMasterKey == other.newMasterKey && + objectPermission == other.objectPermission && + organizationId == other.organizationId && + permissions == other.permissions && + prompts == other.prompts && + rotationInterval == other.rotationInterval && + routerSettings == other.routerSettings && + rpmLimit == other.rpmLimit && + rpmLimitType == other.rpmLimitType && + sendInviteEmail == other.sendInviteEmail && + softBudget == other.softBudget && + spend == other.spend && + tags == other.tags && + teamId == other.teamId && + tpmLimit == other.tpmLimit && + tpmLimitType == other.tpmLimitType && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + aliases, + allowedCacheControls, + allowedPassthroughRoutes, + allowedRoutes, + allowedVectorStoreIndexes, + autoRotate, + blocked, + budgetDuration, + budgetId, + config, + duration, + enforcedParams, + guardrails, + key, + keyAlias, + keyType, + maxBudget, + maxParallelRequests, + metadata, + modelMaxBudget, + modelRpmLimit, + modelTpmLimit, + models, + newKey, + newMasterKey, + objectPermission, + organizationId, + permissions, + prompts, + rotationInterval, + routerSettings, + rpmLimit, + rpmLimitType, + sendInviteEmail, + softBudget, + spend, + tags, + teamId, + tpmLimit, + tpmLimitType, + userId, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "RegenerateKeyRequest{aliases=$aliases, allowedCacheControls=$allowedCacheControls, blocked=$blocked, budgetDuration=$budgetDuration, budgetId=$budgetId, config=$config, duration=$duration, enforcedParams=$enforcedParams, guardrails=$guardrails, key=$key, keyAlias=$keyAlias, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelRpmLimit=$modelRpmLimit, modelTpmLimit=$modelTpmLimit, models=$models, newMasterKey=$newMasterKey, permissions=$permissions, rpmLimit=$rpmLimit, sendInviteEmail=$sendInviteEmail, softBudget=$softBudget, spend=$spend, tags=$tags, teamId=$teamId, tpmLimit=$tpmLimit, userId=$userId, additionalProperties=$additionalProperties}" + "RegenerateKeyRequest{aliases=$aliases, allowedCacheControls=$allowedCacheControls, allowedPassthroughRoutes=$allowedPassthroughRoutes, allowedRoutes=$allowedRoutes, allowedVectorStoreIndexes=$allowedVectorStoreIndexes, autoRotate=$autoRotate, blocked=$blocked, budgetDuration=$budgetDuration, budgetId=$budgetId, config=$config, duration=$duration, enforcedParams=$enforcedParams, guardrails=$guardrails, key=$key, keyAlias=$keyAlias, keyType=$keyType, maxBudget=$maxBudget, maxParallelRequests=$maxParallelRequests, metadata=$metadata, modelMaxBudget=$modelMaxBudget, modelRpmLimit=$modelRpmLimit, modelTpmLimit=$modelTpmLimit, models=$models, newKey=$newKey, newMasterKey=$newMasterKey, objectPermission=$objectPermission, organizationId=$organizationId, permissions=$permissions, prompts=$prompts, rotationInterval=$rotationInterval, routerSettings=$routerSettings, rpmLimit=$rpmLimit, rpmLimitType=$rpmLimitType, sendInviteEmail=$sendInviteEmail, softBudget=$softBudget, spend=$spend, tags=$tags, teamId=$teamId, tpmLimit=$tpmLimit, tpmLimitType=$tpmLimitType, userId=$userId, additionalProperties=$additionalProperties}" } diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseCreateParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseCreateParams.kt index 1580aa8f..b75d04ea 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseCreateParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseCreateParams.kt @@ -4,46 +4,44 @@ package ai.hanzo.api.models.langfuse import ai.hanzo.api.core.JsonValue import ai.hanzo.api.core.Params -import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.http.Headers import ai.hanzo.api.core.http.QueryParams import ai.hanzo.api.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** - * Call Langfuse via LLM proxy. Works with Langfuse SDK. + * Call Langfuse via LiteLLM proxy. Works with Langfuse SDK. * - * [Docs](https://docs.hanzo.ai/docs/pass_through/langfuse) + * [Docs](https://docs.litellm.ai/docs/pass_through/langfuse) */ class LangfuseCreateParams private constructor( - private val endpoint: String, + private val endpoint: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, private val additionalBodyProperties: Map, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [LangfuseCreateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): LangfuseCreateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [LangfuseCreateParams]. */ @JvmStatic fun builder() = Builder() } @@ -63,7 +61,10 @@ private constructor( additionalBodyProperties = langfuseCreateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -189,30 +190,22 @@ private constructor( * Returns an immutable instance of [LangfuseCreateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): LangfuseCreateParams = LangfuseCreateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -225,10 +218,15 @@ private constructor( return true } - return /* spotless:off */ other is LangfuseCreateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is LangfuseCreateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "LangfuseCreateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseCreateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseCreateResponse.kt index 756694a4..3b90081e 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseCreateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseCreateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.langfuse import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class LangfuseCreateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [LangfuseDeleteParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): LangfuseDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [LangfuseDeleteParams]. */ @JvmStatic fun builder() = Builder() } @@ -63,7 +61,10 @@ private constructor( additionalBodyProperties = langfuseDeleteParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -189,30 +190,22 @@ private constructor( * Returns an immutable instance of [LangfuseDeleteParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): LangfuseDeleteParams = LangfuseDeleteParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -225,10 +218,15 @@ private constructor( return true } - return /* spotless:off */ other is LangfuseDeleteParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is LangfuseDeleteParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "LangfuseDeleteParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseDeleteResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseDeleteResponse.kt index fda2510d..eda7d242 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseDeleteResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseDeleteResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.langfuse import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class LangfuseDeleteResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [LangfusePatchParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): LangfusePatchParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [LangfusePatchParams]. */ @JvmStatic fun builder() = Builder() } @@ -63,7 +61,10 @@ private constructor( additionalBodyProperties = langfusePatchParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -189,30 +190,22 @@ private constructor( * Returns an immutable instance of [LangfusePatchParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): LangfusePatchParams = LangfusePatchParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -225,10 +218,15 @@ private constructor( return true } - return /* spotless:off */ other is LangfusePatchParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is LangfusePatchParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "LangfusePatchParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfusePatchResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfusePatchResponse.kt index 61edd829..3734310e 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfusePatchResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfusePatchResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.langfuse import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class LangfusePatchResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap = Optional.ofNullable(endpoint) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [LangfuseRetrieveParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): LangfuseRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [LangfuseRetrieveParams]. */ @JvmStatic fun builder() = Builder() } @@ -55,7 +53,10 @@ private constructor( additionalQueryParams = langfuseRetrieveParams.additionalQueryParams.toBuilder() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -159,17 +160,10 @@ private constructor( * Returns an immutable instance of [LangfuseRetrieveParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): LangfuseRetrieveParams = LangfuseRetrieveParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), ) @@ -177,7 +171,7 @@ private constructor( fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -190,10 +184,13 @@ private constructor( return true } - return /* spotless:off */ other is LangfuseRetrieveParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is LangfuseRetrieveParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(endpoint, additionalHeaders, additionalQueryParams) override fun toString() = "LangfuseRetrieveParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseRetrieveResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseRetrieveResponse.kt index 97a49063..be1aca28 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseRetrieveResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseRetrieveResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.langfuse import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class LangfuseRetrieveResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,31 @@ private constructor(private val additionalProperties: MutableMap, ) : Params { - fun endpoint(): String = endpoint + fun endpoint(): Optional = Optional.ofNullable(endpoint) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { - /** - * Returns a mutable builder for constructing an instance of [LangfuseUpdateParams]. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - */ + @JvmStatic fun none(): LangfuseUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [LangfuseUpdateParams]. */ @JvmStatic fun builder() = Builder() } @@ -63,7 +61,10 @@ private constructor( additionalBodyProperties = langfuseUpdateParams.additionalBodyProperties.toMutableMap() } - fun endpoint(endpoint: String) = apply { this.endpoint = endpoint } + fun endpoint(endpoint: String?) = apply { this.endpoint = endpoint } + + /** Alias for calling [Builder.endpoint] with `endpoint.orElse(null)`. */ + fun endpoint(endpoint: Optional) = endpoint(endpoint.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -189,30 +190,22 @@ private constructor( * Returns an immutable instance of [LangfuseUpdateParams]. * * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .endpoint() - * ``` - * - * @throws IllegalStateException if any required field is unset. */ fun build(): LangfuseUpdateParams = LangfuseUpdateParams( - checkRequired("endpoint", endpoint), + endpoint, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } - @JvmSynthetic - internal fun _body(): Optional> = + fun _body(): Optional> = Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) fun _pathParam(index: Int): String = when (index) { - 0 -> endpoint + 0 -> endpoint ?: "" else -> "" } @@ -225,10 +218,15 @@ private constructor( return true } - return /* spotless:off */ other is LangfuseUpdateParams && endpoint == other.endpoint && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is LangfuseUpdateParams && + endpoint == other.endpoint && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(endpoint, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "LangfuseUpdateParams{endpoint=$endpoint, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseUpdateResponse.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseUpdateResponse.kt index d37b3b58..0c45c4ad 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseUpdateResponse.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/langfuse/LangfuseUpdateResponse.kt @@ -4,6 +4,7 @@ package ai.hanzo.api.models.langfuse import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonValue +import ai.hanzo.api.errors.HanzoInvalidDataException import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator @@ -11,6 +12,7 @@ import java.util.Collections import java.util.Objects class LangfuseUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor(private val additionalProperties: MutableMap) { @JsonCreator private constructor() : this(mutableMapOf()) @@ -81,17 +83,30 @@ private constructor(private val additionalProperties: MutableMap, - private val additionalProperties: MutableMap, -) { - - @JsonCreator - private constructor( - @JsonProperty("api_base") @ExcludeMissing apiBase: JsonField = JsonMissing.of() - ) : this(apiBase, mutableMapOf()) - - /** - * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly - * missing or null (e.g. if the server responded with an unexpected value). - */ - fun apiBase(): String = apiBase.getRequired("api_base") - - /** - * Returns the raw JSON value of [apiBase]. - * - * Unlike [apiBase], this method doesn't throw if the JSON field has an unexpected type. - */ - @JsonProperty("api_base") @ExcludeMissing fun _apiBase(): JsonField = apiBase - - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) - - fun toBuilder() = Builder().from(this) - - companion object { - - /** - * Returns a mutable builder for constructing an instance of - * [ConfigurableClientsideParamsCustomAuth]. - * - * The following fields are required: - * ```java - * .apiBase() - * ``` - */ - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ConfigurableClientsideParamsCustomAuth]. */ - class Builder internal constructor() { - - private var apiBase: JsonField? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from( - configurableClientsideParamsCustomAuth: ConfigurableClientsideParamsCustomAuth - ) = apply { - apiBase = configurableClientsideParamsCustomAuth.apiBase - additionalProperties = - configurableClientsideParamsCustomAuth.additionalProperties.toMutableMap() - } - - fun apiBase(apiBase: String) = apiBase(JsonField.of(apiBase)) - - /** - * Sets [Builder.apiBase] to an arbitrary JSON value. - * - * You should usually call [Builder.apiBase] with a well-typed [String] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported value. - */ - fun apiBase(apiBase: JsonField) = apply { this.apiBase = apiBase } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - /** - * Returns an immutable instance of [ConfigurableClientsideParamsCustomAuth]. - * - * Further updates to this [Builder] will not mutate the returned instance. - * - * The following fields are required: - * ```java - * .apiBase() - * ``` - * - * @throws IllegalStateException if any required field is unset. - */ - fun build(): ConfigurableClientsideParamsCustomAuth = - ConfigurableClientsideParamsCustomAuth( - checkRequired("apiBase", apiBase), - additionalProperties.toMutableMap(), - ) - } - - private var validated: Boolean = false - - fun validate(): ConfigurableClientsideParamsCustomAuth = apply { - if (validated) { - return@apply - } - - apiBase() - validated = true - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ConfigurableClientsideParamsCustomAuth && apiBase == other.apiBase && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(apiBase, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ConfigurableClientsideParamsCustomAuth{apiBase=$apiBase, additionalProperties=$additionalProperties}" -} diff --git a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/model/ModelCreateParams.kt b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/model/ModelCreateParams.kt index 6f63a30f..e6f80eca 100644 --- a/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/model/ModelCreateParams.kt +++ b/hanzo-java-core/src/main/kotlin/ai/hanzo/api/models/model/ModelCreateParams.kt @@ -4,11 +4,13 @@ package ai.hanzo.api.models.model import ai.hanzo.api.core.BaseDeserializer import ai.hanzo.api.core.BaseSerializer +import ai.hanzo.api.core.Enum import ai.hanzo.api.core.ExcludeMissing import ai.hanzo.api.core.JsonField import ai.hanzo.api.core.JsonMissing import ai.hanzo.api.core.JsonValue import ai.hanzo.api.core.Params +import ai.hanzo.api.core.allMaxBy import ai.hanzo.api.core.checkKnown import ai.hanzo.api.core.checkRequired import ai.hanzo.api.core.getOrThrow @@ -41,12 +43,12 @@ private constructor( ) : Params { /** - * LLM Params with 'model' requirement - used for completions + * LiteLLM Params with 'model' requirement - used for completions * * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly * missing or null (e.g. if the server responded with an unexpected value). */ - fun llmParams(): LlmParams = body.llmParams() + fun litellmParams(): LitellmParams = body.litellmParams() /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is unexpectedly @@ -61,11 +63,11 @@ private constructor( fun modelName(): String = body.modelName() /** - * Returns the raw JSON value of [llmParams]. + * Returns the raw JSON value of [litellmParams]. * - * Unlike [llmParams], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [litellmParams], this method doesn't throw if the JSON field has an unexpected type. */ - fun _llmParams(): JsonField = body._llmParams() + fun _litellmParams(): JsonField = body._litellmParams() /** * Returns the raw JSON value of [modelInfo]. @@ -83,8 +85,10 @@ private constructor( fun _additionalBodyProperties(): Map = body._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -96,7 +100,7 @@ private constructor( * * The following fields are required: * ```java - * .llmParams() + * .litellmParams() * .modelInfo() * .modelName() * ``` @@ -118,17 +122,32 @@ private constructor( additionalQueryParams = modelCreateParams.additionalQueryParams.toBuilder() } - /** LLM Params with 'model' requirement - used for completions */ - fun llmParams(llmParams: LlmParams) = apply { body.llmParams(llmParams) } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [litellmParams] + * - [modelInfo] + * - [modelName] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** LiteLLM Params with 'model' requirement - used for completions */ + fun litellmParams(litellmParams: LitellmParams) = apply { + body.litellmParams(litellmParams) + } /** - * Sets [Builder.llmParams] to an arbitrary JSON value. + * Sets [Builder.litellmParams] to an arbitrary JSON value. * - * You should usually call [Builder.llmParams] with a well-typed [LlmParams] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * You should usually call [Builder.litellmParams] with a well-typed [LitellmParams] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun llmParams(llmParams: JsonField) = apply { body.llmParams(llmParams) } + fun litellmParams(litellmParams: JsonField) = apply { + body.litellmParams(litellmParams) + } fun modelInfo(modelInfo: ModelInfo) = apply { body.modelInfo(modelInfo) } @@ -276,7 +295,7 @@ private constructor( * * The following fields are required: * ```java - * .llmParams() + * .litellmParams() * .modelInfo() * .modelName() * ``` @@ -291,15 +310,16 @@ private constructor( ) } - @JvmSynthetic internal fun _body(): Body = body + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - private val llmParams: JsonField, + private val litellmParams: JsonField, private val modelInfo: JsonField, private val modelName: JsonField, private val additionalProperties: MutableMap, @@ -307,24 +327,24 @@ private constructor( @JsonCreator private constructor( - @JsonProperty("llm_params") + @JsonProperty("litellm_params") @ExcludeMissing - llmParams: JsonField = JsonMissing.of(), + litellmParams: JsonField = JsonMissing.of(), @JsonProperty("model_info") @ExcludeMissing modelInfo: JsonField = JsonMissing.of(), @JsonProperty("model_name") @ExcludeMissing modelName: JsonField = JsonMissing.of(), - ) : this(llmParams, modelInfo, modelName, mutableMapOf()) + ) : this(litellmParams, modelInfo, modelName, mutableMapOf()) /** - * LLM Params with 'model' requirement - used for completions + * LiteLLM Params with 'model' requirement - used for completions * * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is * unexpectedly missing or null (e.g. if the server responded with an unexpected value). */ - fun llmParams(): LlmParams = llmParams.getRequired("llm_params") + fun litellmParams(): LitellmParams = litellmParams.getRequired("litellm_params") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is @@ -339,13 +359,14 @@ private constructor( fun modelName(): String = modelName.getRequired("model_name") /** - * Returns the raw JSON value of [llmParams]. + * Returns the raw JSON value of [litellmParams]. * - * Unlike [llmParams], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [litellmParams], this method doesn't throw if the JSON field has an unexpected + * type. */ - @JsonProperty("llm_params") + @JsonProperty("litellm_params") @ExcludeMissing - fun _llmParams(): JsonField = llmParams + fun _litellmParams(): JsonField = litellmParams /** * Returns the raw JSON value of [modelInfo]. @@ -382,7 +403,7 @@ private constructor( * * The following fields are required: * ```java - * .llmParams() + * .litellmParams() * .modelInfo() * .modelName() * ``` @@ -393,30 +414,33 @@ private constructor( /** A builder for [Body]. */ class Builder internal constructor() { - private var llmParams: JsonField? = null + private var litellmParams: JsonField? = null private var modelInfo: JsonField? = null private var modelName: JsonField? = null private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(body: Body) = apply { - llmParams = body.llmParams + litellmParams = body.litellmParams modelInfo = body.modelInfo modelName = body.modelName additionalProperties = body.additionalProperties.toMutableMap() } - /** LLM Params with 'model' requirement - used for completions */ - fun llmParams(llmParams: LlmParams) = llmParams(JsonField.of(llmParams)) + /** LiteLLM Params with 'model' requirement - used for completions */ + fun litellmParams(litellmParams: LitellmParams) = + litellmParams(JsonField.of(litellmParams)) /** - * Sets [Builder.llmParams] to an arbitrary JSON value. + * Sets [Builder.litellmParams] to an arbitrary JSON value. * - * You should usually call [Builder.llmParams] with a well-typed [LlmParams] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * You should usually call [Builder.litellmParams] with a well-typed [LitellmParams] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. */ - fun llmParams(llmParams: JsonField) = apply { this.llmParams = llmParams } + fun litellmParams(litellmParams: JsonField) = apply { + this.litellmParams = litellmParams + } fun modelInfo(modelInfo: ModelInfo) = modelInfo(JsonField.of(modelInfo)) @@ -466,7 +490,7 @@ private constructor( * * The following fields are required: * ```java - * .llmParams() + * .litellmParams() * .modelInfo() * .modelName() * ``` @@ -475,7 +499,7 @@ private constructor( */ fun build(): Body = Body( - checkRequired("llmParams", llmParams), + checkRequired("litellmParams", litellmParams), checkRequired("modelInfo", modelInfo), checkRequired("modelName", modelName), additionalProperties.toMutableMap(), @@ -489,61 +513,144 @@ private constructor( return@apply } - llmParams().validate() + litellmParams().validate() modelInfo().validate() modelName() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (litellmParams.asKnown().getOrNull()?.validity() ?: 0) + + (modelInfo.asKnown().getOrNull()?.validity() ?: 0) + + (if (modelName.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Body && llmParams == other.llmParams && modelInfo == other.modelInfo && modelName == other.modelName && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Body && + litellmParams == other.litellmParams && + modelInfo == other.modelInfo && + modelName == other.modelName && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(llmParams, modelInfo, modelName, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash(litellmParams, modelInfo, modelName, additionalProperties) + } override fun hashCode(): Int = hashCode override fun toString() = - "Body{llmParams=$llmParams, modelInfo=$modelInfo, modelName=$modelName, additionalProperties=$additionalProperties}" + "Body{litellmParams=$litellmParams, modelInfo=$modelInfo, modelName=$modelName, additionalProperties=$additionalProperties}" } - /** LLM Params with 'model' requirement - used for completions */ - class LlmParams + /** LiteLLM Params with 'model' requirement - used for completions */ + class LitellmParams + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val model: JsonField, private val apiBase: JsonField, private val apiKey: JsonField, private val apiVersion: JsonField, + private val autoRouterConfig: JsonField, + private val autoRouterConfigPath: JsonField, + private val autoRouterDefaultModel: JsonField, + private val autoRouterEmbeddingModel: JsonField, private val awsAccessKeyId: JsonField, + private val awsBedrockRuntimeEndpoint: JsonField, private val awsRegionName: JsonField, private val awsSecretAccessKey: JsonField, private val budgetDuration: JsonField, + private val cacheCreationInputAudioTokenCost: JsonField, + private val cacheCreationInputTokenCost: JsonField, + private val cacheCreationInputTokenCostAbove1hr: JsonField, + private val cacheCreationInputTokenCostAbove200kTokens: JsonField, + private val cacheReadInputAudioTokenCost: JsonField, + private val cacheReadInputTokenCost: JsonField, + private val cacheReadInputTokenCostAbove200kTokens: JsonField, + private val cacheReadInputTokenCostFlex: JsonField, + private val cacheReadInputTokenCostPriority: JsonField, + private val citationCostPerToken: JsonField, private val configurableClientsideAuthParams: JsonField>, private val customLlmProvider: JsonField, + private val gcsBucketName: JsonField, + private val inputCostPerAudioPerSecond: JsonField, + private val inputCostPerAudioPerSecondAbove128kTokens: JsonField, + private val inputCostPerAudioToken: JsonField, + private val inputCostPerCharacter: JsonField, + private val inputCostPerCharacterAbove128kTokens: JsonField, + private val inputCostPerImage: JsonField, + private val inputCostPerImageAbove128kTokens: JsonField, + private val inputCostPerPixel: JsonField, + private val inputCostPerQuery: JsonField, private val inputCostPerSecond: JsonField, private val inputCostPerToken: JsonField, - private val llmTraceId: JsonField, + private val inputCostPerTokenAbove128kTokens: JsonField, + private val inputCostPerTokenAbove200kTokens: JsonField, + private val inputCostPerTokenBatches: JsonField, + private val inputCostPerTokenCacheHit: JsonField, + private val inputCostPerTokenFlex: JsonField, + private val inputCostPerTokenPriority: JsonField, + private val inputCostPerVideoPerSecond: JsonField, + private val inputCostPerVideoPerSecondAbove128kTokens: JsonField, + private val inputCostPerVideoPerSecondAbove15sInterval: JsonField, + private val inputCostPerVideoPerSecondAbove8sInterval: JsonField, + private val litellmCredentialName: JsonField, + private val litellmTraceId: JsonField, private val maxBudget: JsonField, private val maxFileSizeMb: JsonField, private val maxRetries: JsonField, private val mergeReasoningContentInChoices: JsonField, - private val modelInfo: JsonValue, + private val milvusTextField: JsonField, + private val mockResponse: JsonField, + private val modelInfo: JsonField, private val organization: JsonField, + private val outputCostPerAudioPerSecond: JsonField, + private val outputCostPerAudioToken: JsonField, + private val outputCostPerCharacter: JsonField, + private val outputCostPerCharacterAbove128kTokens: JsonField, + private val outputCostPerImage: JsonField, + private val outputCostPerImageToken: JsonField, + private val outputCostPerPixel: JsonField, + private val outputCostPerReasoningToken: JsonField, private val outputCostPerSecond: JsonField, private val outputCostPerToken: JsonField, + private val outputCostPerTokenAbove128kTokens: JsonField, + private val outputCostPerTokenAbove200kTokens: JsonField, + private val outputCostPerTokenBatches: JsonField, + private val outputCostPerTokenFlex: JsonField, + private val outputCostPerTokenPriority: JsonField, + private val outputCostPerVideoPerSecond: JsonField, private val regionName: JsonField, private val rpm: JsonField, + private val s3BucketName: JsonField, + private val s3EncryptionKeyId: JsonField, + private val searchContextCostPerQuery: JsonField, private val streamTimeout: JsonField, + private val tieredPricing: JsonField>, private val timeout: JsonField, private val tpm: JsonField, private val useInPassThrough: JsonField, + private val useLitellmProxy: JsonField, + private val vectorStoreId: JsonField, private val vertexCredentials: JsonField, private val vertexLocation: JsonField, private val vertexProject: JsonField, @@ -559,9 +666,24 @@ private constructor( @JsonProperty("api_version") @ExcludeMissing apiVersion: JsonField = JsonMissing.of(), + @JsonProperty("auto_router_config") + @ExcludeMissing + autoRouterConfig: JsonField = JsonMissing.of(), + @JsonProperty("auto_router_config_path") + @ExcludeMissing + autoRouterConfigPath: JsonField = JsonMissing.of(), + @JsonProperty("auto_router_default_model") + @ExcludeMissing + autoRouterDefaultModel: JsonField = JsonMissing.of(), + @JsonProperty("auto_router_embedding_model") + @ExcludeMissing + autoRouterEmbeddingModel: JsonField = JsonMissing.of(), @JsonProperty("aws_access_key_id") @ExcludeMissing awsAccessKeyId: JsonField = JsonMissing.of(), + @JsonProperty("aws_bedrock_runtime_endpoint") + @ExcludeMissing + awsBedrockRuntimeEndpoint: JsonField = JsonMissing.of(), @JsonProperty("aws_region_name") @ExcludeMissing awsRegionName: JsonField = JsonMissing.of(), @@ -571,6 +693,36 @@ private constructor( @JsonProperty("budget_duration") @ExcludeMissing budgetDuration: JsonField = JsonMissing.of(), + @JsonProperty("cache_creation_input_audio_token_cost") + @ExcludeMissing + cacheCreationInputAudioTokenCost: JsonField = JsonMissing.of(), + @JsonProperty("cache_creation_input_token_cost") + @ExcludeMissing + cacheCreationInputTokenCost: JsonField = JsonMissing.of(), + @JsonProperty("cache_creation_input_token_cost_above_1hr") + @ExcludeMissing + cacheCreationInputTokenCostAbove1hr: JsonField = JsonMissing.of(), + @JsonProperty("cache_creation_input_token_cost_above_200k_tokens") + @ExcludeMissing + cacheCreationInputTokenCostAbove200kTokens: JsonField = JsonMissing.of(), + @JsonProperty("cache_read_input_audio_token_cost") + @ExcludeMissing + cacheReadInputAudioTokenCost: JsonField = JsonMissing.of(), + @JsonProperty("cache_read_input_token_cost") + @ExcludeMissing + cacheReadInputTokenCost: JsonField = JsonMissing.of(), + @JsonProperty("cache_read_input_token_cost_above_200k_tokens") + @ExcludeMissing + cacheReadInputTokenCostAbove200kTokens: JsonField = JsonMissing.of(), + @JsonProperty("cache_read_input_token_cost_flex") + @ExcludeMissing + cacheReadInputTokenCostFlex: JsonField = JsonMissing.of(), + @JsonProperty("cache_read_input_token_cost_priority") + @ExcludeMissing + cacheReadInputTokenCostPriority: JsonField = JsonMissing.of(), + @JsonProperty("citation_cost_per_token") + @ExcludeMissing + citationCostPerToken: JsonField = JsonMissing.of(), @JsonProperty("configurable_clientside_auth_params") @ExcludeMissing configurableClientsideAuthParams: JsonField> = @@ -578,15 +730,78 @@ private constructor( @JsonProperty("custom_llm_provider") @ExcludeMissing customLlmProvider: JsonField = JsonMissing.of(), + @JsonProperty("gcs_bucket_name") + @ExcludeMissing + gcsBucketName: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_audio_per_second") + @ExcludeMissing + inputCostPerAudioPerSecond: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_audio_per_second_above_128k_tokens") + @ExcludeMissing + inputCostPerAudioPerSecondAbove128kTokens: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_audio_token") + @ExcludeMissing + inputCostPerAudioToken: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_character") + @ExcludeMissing + inputCostPerCharacter: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_character_above_128k_tokens") + @ExcludeMissing + inputCostPerCharacterAbove128kTokens: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_image") + @ExcludeMissing + inputCostPerImage: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_image_above_128k_tokens") + @ExcludeMissing + inputCostPerImageAbove128kTokens: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_pixel") + @ExcludeMissing + inputCostPerPixel: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_query") + @ExcludeMissing + inputCostPerQuery: JsonField = JsonMissing.of(), @JsonProperty("input_cost_per_second") @ExcludeMissing inputCostPerSecond: JsonField = JsonMissing.of(), @JsonProperty("input_cost_per_token") @ExcludeMissing inputCostPerToken: JsonField = JsonMissing.of(), - @JsonProperty("llm_trace_id") + @JsonProperty("input_cost_per_token_above_128k_tokens") @ExcludeMissing - llmTraceId: JsonField = JsonMissing.of(), + inputCostPerTokenAbove128kTokens: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_token_above_200k_tokens") + @ExcludeMissing + inputCostPerTokenAbove200kTokens: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_token_batches") + @ExcludeMissing + inputCostPerTokenBatches: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_token_cache_hit") + @ExcludeMissing + inputCostPerTokenCacheHit: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_token_flex") + @ExcludeMissing + inputCostPerTokenFlex: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_token_priority") + @ExcludeMissing + inputCostPerTokenPriority: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_video_per_second") + @ExcludeMissing + inputCostPerVideoPerSecond: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_video_per_second_above_128k_tokens") + @ExcludeMissing + inputCostPerVideoPerSecondAbove128kTokens: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_video_per_second_above_15s_interval") + @ExcludeMissing + inputCostPerVideoPerSecondAbove15sInterval: JsonField = JsonMissing.of(), + @JsonProperty("input_cost_per_video_per_second_above_8s_interval") + @ExcludeMissing + inputCostPerVideoPerSecondAbove8sInterval: JsonField = JsonMissing.of(), + @JsonProperty("litellm_credential_name") + @ExcludeMissing + litellmCredentialName: JsonField = JsonMissing.of(), + @JsonProperty("litellm_trace_id") + @ExcludeMissing + litellmTraceId: JsonField = JsonMissing.of(), @JsonProperty("max_budget") @ExcludeMissing maxBudget: JsonField = JsonMissing.of(), @@ -599,28 +814,96 @@ private constructor( @JsonProperty("merge_reasoning_content_in_choices") @ExcludeMissing mergeReasoningContentInChoices: JsonField = JsonMissing.of(), - @JsonProperty("model_info") @ExcludeMissing modelInfo: JsonValue = JsonMissing.of(), + @JsonProperty("milvus_text_field") + @ExcludeMissing + milvusTextField: JsonField = JsonMissing.of(), + @JsonProperty("mock_response") + @ExcludeMissing + mockResponse: JsonField = JsonMissing.of(), + @JsonProperty("model_info") + @ExcludeMissing + modelInfo: JsonField = JsonMissing.of(), @JsonProperty("organization") @ExcludeMissing organization: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_audio_per_second") + @ExcludeMissing + outputCostPerAudioPerSecond: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_audio_token") + @ExcludeMissing + outputCostPerAudioToken: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_character") + @ExcludeMissing + outputCostPerCharacter: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_character_above_128k_tokens") + @ExcludeMissing + outputCostPerCharacterAbove128kTokens: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_image") + @ExcludeMissing + outputCostPerImage: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_image_token") + @ExcludeMissing + outputCostPerImageToken: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_pixel") + @ExcludeMissing + outputCostPerPixel: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_reasoning_token") + @ExcludeMissing + outputCostPerReasoningToken: JsonField = JsonMissing.of(), @JsonProperty("output_cost_per_second") @ExcludeMissing outputCostPerSecond: JsonField = JsonMissing.of(), @JsonProperty("output_cost_per_token") @ExcludeMissing outputCostPerToken: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_token_above_128k_tokens") + @ExcludeMissing + outputCostPerTokenAbove128kTokens: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_token_above_200k_tokens") + @ExcludeMissing + outputCostPerTokenAbove200kTokens: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_token_batches") + @ExcludeMissing + outputCostPerTokenBatches: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_token_flex") + @ExcludeMissing + outputCostPerTokenFlex: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_token_priority") + @ExcludeMissing + outputCostPerTokenPriority: JsonField = JsonMissing.of(), + @JsonProperty("output_cost_per_video_per_second") + @ExcludeMissing + outputCostPerVideoPerSecond: JsonField = JsonMissing.of(), @JsonProperty("region_name") @ExcludeMissing regionName: JsonField = JsonMissing.of(), @JsonProperty("rpm") @ExcludeMissing rpm: JsonField = JsonMissing.of(), + @JsonProperty("s3_bucket_name") + @ExcludeMissing + s3BucketName: JsonField = JsonMissing.of(), + @JsonProperty("s3_encryption_key_id") + @ExcludeMissing + s3EncryptionKeyId: JsonField = JsonMissing.of(), + @JsonProperty("search_context_cost_per_query") + @ExcludeMissing + searchContextCostPerQuery: JsonField = JsonMissing.of(), @JsonProperty("stream_timeout") @ExcludeMissing streamTimeout: JsonField = JsonMissing.of(), + @JsonProperty("tiered_pricing") + @ExcludeMissing + tieredPricing: JsonField> = JsonMissing.of(), @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), @JsonProperty("tpm") @ExcludeMissing tpm: JsonField = JsonMissing.of(), @JsonProperty("use_in_pass_through") @ExcludeMissing useInPassThrough: JsonField = JsonMissing.of(), + @JsonProperty("use_litellm_proxy") + @ExcludeMissing + useLitellmProxy: JsonField = JsonMissing.of(), + @JsonProperty("vector_store_id") + @ExcludeMissing + vectorStoreId: JsonField = JsonMissing.of(), @JsonProperty("vertex_credentials") @ExcludeMissing vertexCredentials: JsonField = JsonMissing.of(), @@ -638,29 +921,87 @@ private constructor( apiBase, apiKey, apiVersion, + autoRouterConfig, + autoRouterConfigPath, + autoRouterDefaultModel, + autoRouterEmbeddingModel, awsAccessKeyId, + awsBedrockRuntimeEndpoint, awsRegionName, awsSecretAccessKey, budgetDuration, + cacheCreationInputAudioTokenCost, + cacheCreationInputTokenCost, + cacheCreationInputTokenCostAbove1hr, + cacheCreationInputTokenCostAbove200kTokens, + cacheReadInputAudioTokenCost, + cacheReadInputTokenCost, + cacheReadInputTokenCostAbove200kTokens, + cacheReadInputTokenCostFlex, + cacheReadInputTokenCostPriority, + citationCostPerToken, configurableClientsideAuthParams, customLlmProvider, + gcsBucketName, + inputCostPerAudioPerSecond, + inputCostPerAudioPerSecondAbove128kTokens, + inputCostPerAudioToken, + inputCostPerCharacter, + inputCostPerCharacterAbove128kTokens, + inputCostPerImage, + inputCostPerImageAbove128kTokens, + inputCostPerPixel, + inputCostPerQuery, inputCostPerSecond, inputCostPerToken, - llmTraceId, + inputCostPerTokenAbove128kTokens, + inputCostPerTokenAbove200kTokens, + inputCostPerTokenBatches, + inputCostPerTokenCacheHit, + inputCostPerTokenFlex, + inputCostPerTokenPriority, + inputCostPerVideoPerSecond, + inputCostPerVideoPerSecondAbove128kTokens, + inputCostPerVideoPerSecondAbove15sInterval, + inputCostPerVideoPerSecondAbove8sInterval, + litellmCredentialName, + litellmTraceId, maxBudget, maxFileSizeMb, maxRetries, mergeReasoningContentInChoices, + milvusTextField, + mockResponse, modelInfo, organization, + outputCostPerAudioPerSecond, + outputCostPerAudioToken, + outputCostPerCharacter, + outputCostPerCharacterAbove128kTokens, + outputCostPerImage, + outputCostPerImageToken, + outputCostPerPixel, + outputCostPerReasoningToken, outputCostPerSecond, outputCostPerToken, + outputCostPerTokenAbove128kTokens, + outputCostPerTokenAbove200kTokens, + outputCostPerTokenBatches, + outputCostPerTokenFlex, + outputCostPerTokenPriority, + outputCostPerVideoPerSecond, regionName, rpm, + s3BucketName, + s3EncryptionKeyId, + searchContextCostPerQuery, streamTimeout, + tieredPricing, timeout, tpm, useInPassThrough, + useLitellmProxy, + vectorStoreId, vertexCredentials, vertexLocation, vertexProject, @@ -678,1519 +1019,11993 @@ private constructor( * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun apiBase(): Optional = Optional.ofNullable(apiBase.getNullable("api_base")) + fun apiBase(): Optional = apiBase.getOptional("api_base") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun apiKey(): Optional = Optional.ofNullable(apiKey.getNullable("api_key")) + fun apiKey(): Optional = apiKey.getOptional("api_key") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun apiVersion(): Optional = - Optional.ofNullable(apiVersion.getNullable("api_version")) + fun apiVersion(): Optional = apiVersion.getOptional("api_version") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun awsAccessKeyId(): Optional = - Optional.ofNullable(awsAccessKeyId.getNullable("aws_access_key_id")) + fun autoRouterConfig(): Optional = + autoRouterConfig.getOptional("auto_router_config") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun awsRegionName(): Optional = - Optional.ofNullable(awsRegionName.getNullable("aws_region_name")) + fun autoRouterConfigPath(): Optional = + autoRouterConfigPath.getOptional("auto_router_config_path") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun awsSecretAccessKey(): Optional = - Optional.ofNullable(awsSecretAccessKey.getNullable("aws_secret_access_key")) + fun autoRouterDefaultModel(): Optional = + autoRouterDefaultModel.getOptional("auto_router_default_model") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun budgetDuration(): Optional = - Optional.ofNullable(budgetDuration.getNullable("budget_duration")) + fun autoRouterEmbeddingModel(): Optional = + autoRouterEmbeddingModel.getOptional("auto_router_embedding_model") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun configurableClientsideAuthParams(): Optional> = - Optional.ofNullable( - configurableClientsideAuthParams.getNullable("configurable_clientside_auth_params") - ) + fun awsAccessKeyId(): Optional = awsAccessKeyId.getOptional("aws_access_key_id") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun customLlmProvider(): Optional = - Optional.ofNullable(customLlmProvider.getNullable("custom_llm_provider")) + fun awsBedrockRuntimeEndpoint(): Optional = + awsBedrockRuntimeEndpoint.getOptional("aws_bedrock_runtime_endpoint") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun inputCostPerSecond(): Optional = - Optional.ofNullable(inputCostPerSecond.getNullable("input_cost_per_second")) + fun awsRegionName(): Optional = awsRegionName.getOptional("aws_region_name") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun inputCostPerToken(): Optional = - Optional.ofNullable(inputCostPerToken.getNullable("input_cost_per_token")) + fun awsSecretAccessKey(): Optional = + awsSecretAccessKey.getOptional("aws_secret_access_key") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun llmTraceId(): Optional = - Optional.ofNullable(llmTraceId.getNullable("llm_trace_id")) + fun budgetDuration(): Optional = budgetDuration.getOptional("budget_duration") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun maxBudget(): Optional = Optional.ofNullable(maxBudget.getNullable("max_budget")) + fun cacheCreationInputAudioTokenCost(): Optional = + cacheCreationInputAudioTokenCost.getOptional("cache_creation_input_audio_token_cost") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun maxFileSizeMb(): Optional = - Optional.ofNullable(maxFileSizeMb.getNullable("max_file_size_mb")) + fun cacheCreationInputTokenCost(): Optional = + cacheCreationInputTokenCost.getOptional("cache_creation_input_token_cost") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun maxRetries(): Optional = - Optional.ofNullable(maxRetries.getNullable("max_retries")) + fun cacheCreationInputTokenCostAbove1hr(): Optional = + cacheCreationInputTokenCostAbove1hr.getOptional( + "cache_creation_input_token_cost_above_1hr" + ) /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun mergeReasoningContentInChoices(): Optional = - Optional.ofNullable( - mergeReasoningContentInChoices.getNullable("merge_reasoning_content_in_choices") + fun cacheCreationInputTokenCostAbove200kTokens(): Optional = + cacheCreationInputTokenCostAbove200kTokens.getOptional( + "cache_creation_input_token_cost_above_200k_tokens" ) - @JsonProperty("model_info") @ExcludeMissing fun _modelInfo(): JsonValue = modelInfo + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cacheReadInputAudioTokenCost(): Optional = + cacheReadInputAudioTokenCost.getOptional("cache_read_input_audio_token_cost") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun organization(): Optional = - Optional.ofNullable(organization.getNullable("organization")) + fun cacheReadInputTokenCost(): Optional = + cacheReadInputTokenCost.getOptional("cache_read_input_token_cost") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun outputCostPerSecond(): Optional = - Optional.ofNullable(outputCostPerSecond.getNullable("output_cost_per_second")) + fun cacheReadInputTokenCostAbove200kTokens(): Optional = + cacheReadInputTokenCostAbove200kTokens.getOptional( + "cache_read_input_token_cost_above_200k_tokens" + ) /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun outputCostPerToken(): Optional = - Optional.ofNullable(outputCostPerToken.getNullable("output_cost_per_token")) + fun cacheReadInputTokenCostFlex(): Optional = + cacheReadInputTokenCostFlex.getOptional("cache_read_input_token_cost_flex") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun regionName(): Optional = - Optional.ofNullable(regionName.getNullable("region_name")) + fun cacheReadInputTokenCostPriority(): Optional = + cacheReadInputTokenCostPriority.getOptional("cache_read_input_token_cost_priority") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun rpm(): Optional = Optional.ofNullable(rpm.getNullable("rpm")) + fun citationCostPerToken(): Optional = + citationCostPerToken.getOptional("citation_cost_per_token") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun streamTimeout(): Optional = - Optional.ofNullable(streamTimeout.getNullable("stream_timeout")) + fun configurableClientsideAuthParams(): Optional> = + configurableClientsideAuthParams.getOptional("configurable_clientside_auth_params") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun timeout(): Optional = Optional.ofNullable(timeout.getNullable("timeout")) + fun customLlmProvider(): Optional = + customLlmProvider.getOptional("custom_llm_provider") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun tpm(): Optional = Optional.ofNullable(tpm.getNullable("tpm")) + fun gcsBucketName(): Optional = gcsBucketName.getOptional("gcs_bucket_name") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun useInPassThrough(): Optional = - Optional.ofNullable(useInPassThrough.getNullable("use_in_pass_through")) + fun inputCostPerAudioPerSecond(): Optional = + inputCostPerAudioPerSecond.getOptional("input_cost_per_audio_per_second") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun vertexCredentials(): Optional = - Optional.ofNullable(vertexCredentials.getNullable("vertex_credentials")) + fun inputCostPerAudioPerSecondAbove128kTokens(): Optional = + inputCostPerAudioPerSecondAbove128kTokens.getOptional( + "input_cost_per_audio_per_second_above_128k_tokens" + ) /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun vertexLocation(): Optional = - Optional.ofNullable(vertexLocation.getNullable("vertex_location")) + fun inputCostPerAudioToken(): Optional = + inputCostPerAudioToken.getOptional("input_cost_per_audio_token") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun vertexProject(): Optional = - Optional.ofNullable(vertexProject.getNullable("vertex_project")) + fun inputCostPerCharacter(): Optional = + inputCostPerCharacter.getOptional("input_cost_per_character") /** * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun watsonxRegionName(): Optional = - Optional.ofNullable(watsonxRegionName.getNullable("watsonx_region_name")) + fun inputCostPerCharacterAbove128kTokens(): Optional = + inputCostPerCharacterAbove128kTokens.getOptional( + "input_cost_per_character_above_128k_tokens" + ) /** - * Returns the raw JSON value of [model]. - * - * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + fun inputCostPerImage(): Optional = + inputCostPerImage.getOptional("input_cost_per_image") /** - * Returns the raw JSON value of [apiBase]. - * - * Unlike [apiBase], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("api_base") @ExcludeMissing fun _apiBase(): JsonField = apiBase + fun inputCostPerImageAbove128kTokens(): Optional = + inputCostPerImageAbove128kTokens.getOptional("input_cost_per_image_above_128k_tokens") /** - * Returns the raw JSON value of [apiKey]. - * - * Unlike [apiKey], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("api_key") @ExcludeMissing fun _apiKey(): JsonField = apiKey + fun inputCostPerPixel(): Optional = + inputCostPerPixel.getOptional("input_cost_per_pixel") /** - * Returns the raw JSON value of [apiVersion]. - * - * Unlike [apiVersion], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("api_version") - @ExcludeMissing - fun _apiVersion(): JsonField = apiVersion + fun inputCostPerQuery(): Optional = + inputCostPerQuery.getOptional("input_cost_per_query") /** - * Returns the raw JSON value of [awsAccessKeyId]. - * - * Unlike [awsAccessKeyId], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("aws_access_key_id") - @ExcludeMissing - fun _awsAccessKeyId(): JsonField = awsAccessKeyId + fun inputCostPerSecond(): Optional = + inputCostPerSecond.getOptional("input_cost_per_second") /** - * Returns the raw JSON value of [awsRegionName]. - * - * Unlike [awsRegionName], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("aws_region_name") - @ExcludeMissing - fun _awsRegionName(): JsonField = awsRegionName + fun inputCostPerToken(): Optional = + inputCostPerToken.getOptional("input_cost_per_token") /** - * Returns the raw JSON value of [awsSecretAccessKey]. - * - * Unlike [awsSecretAccessKey], this method doesn't throw if the JSON field has an - * unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("aws_secret_access_key") - @ExcludeMissing - fun _awsSecretAccessKey(): JsonField = awsSecretAccessKey + fun inputCostPerTokenAbove128kTokens(): Optional = + inputCostPerTokenAbove128kTokens.getOptional("input_cost_per_token_above_128k_tokens") /** - * Returns the raw JSON value of [budgetDuration]. - * - * Unlike [budgetDuration], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("budget_duration") - @ExcludeMissing - fun _budgetDuration(): JsonField = budgetDuration + fun inputCostPerTokenAbove200kTokens(): Optional = + inputCostPerTokenAbove200kTokens.getOptional("input_cost_per_token_above_200k_tokens") /** - * Returns the raw JSON value of [configurableClientsideAuthParams]. - * - * Unlike [configurableClientsideAuthParams], this method doesn't throw if the JSON field - * has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("configurable_clientside_auth_params") - @ExcludeMissing - fun _configurableClientsideAuthParams(): JsonField> = - configurableClientsideAuthParams + fun inputCostPerTokenBatches(): Optional = + inputCostPerTokenBatches.getOptional("input_cost_per_token_batches") /** - * Returns the raw JSON value of [customLlmProvider]. - * - * Unlike [customLlmProvider], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("custom_llm_provider") - @ExcludeMissing - fun _customLlmProvider(): JsonField = customLlmProvider + fun inputCostPerTokenCacheHit(): Optional = + inputCostPerTokenCacheHit.getOptional("input_cost_per_token_cache_hit") /** - * Returns the raw JSON value of [inputCostPerSecond]. - * - * Unlike [inputCostPerSecond], this method doesn't throw if the JSON field has an - * unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("input_cost_per_second") - @ExcludeMissing - fun _inputCostPerSecond(): JsonField = inputCostPerSecond + fun inputCostPerTokenFlex(): Optional = + inputCostPerTokenFlex.getOptional("input_cost_per_token_flex") /** - * Returns the raw JSON value of [inputCostPerToken]. - * - * Unlike [inputCostPerToken], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("input_cost_per_token") - @ExcludeMissing - fun _inputCostPerToken(): JsonField = inputCostPerToken + fun inputCostPerTokenPriority(): Optional = + inputCostPerTokenPriority.getOptional("input_cost_per_token_priority") /** - * Returns the raw JSON value of [llmTraceId]. - * - * Unlike [llmTraceId], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("llm_trace_id") - @ExcludeMissing - fun _llmTraceId(): JsonField = llmTraceId + fun inputCostPerVideoPerSecond(): Optional = + inputCostPerVideoPerSecond.getOptional("input_cost_per_video_per_second") /** - * Returns the raw JSON value of [maxBudget]. - * - * Unlike [maxBudget], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("max_budget") @ExcludeMissing fun _maxBudget(): JsonField = maxBudget + fun inputCostPerVideoPerSecondAbove128kTokens(): Optional = + inputCostPerVideoPerSecondAbove128kTokens.getOptional( + "input_cost_per_video_per_second_above_128k_tokens" + ) /** - * Returns the raw JSON value of [maxFileSizeMb]. - * - * Unlike [maxFileSizeMb], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("max_file_size_mb") - @ExcludeMissing - fun _maxFileSizeMb(): JsonField = maxFileSizeMb + fun inputCostPerVideoPerSecondAbove15sInterval(): Optional = + inputCostPerVideoPerSecondAbove15sInterval.getOptional( + "input_cost_per_video_per_second_above_15s_interval" + ) /** - * Returns the raw JSON value of [maxRetries]. - * - * Unlike [maxRetries], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("max_retries") @ExcludeMissing fun _maxRetries(): JsonField = maxRetries + fun inputCostPerVideoPerSecondAbove8sInterval(): Optional = + inputCostPerVideoPerSecondAbove8sInterval.getOptional( + "input_cost_per_video_per_second_above_8s_interval" + ) /** - * Returns the raw JSON value of [mergeReasoningContentInChoices]. - * - * Unlike [mergeReasoningContentInChoices], this method doesn't throw if the JSON field has - * an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("merge_reasoning_content_in_choices") - @ExcludeMissing - fun _mergeReasoningContentInChoices(): JsonField = mergeReasoningContentInChoices + fun litellmCredentialName(): Optional = + litellmCredentialName.getOptional("litellm_credential_name") /** - * Returns the raw JSON value of [organization]. - * - * Unlike [organization], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("organization") - @ExcludeMissing - fun _organization(): JsonField = organization + fun litellmTraceId(): Optional = litellmTraceId.getOptional("litellm_trace_id") /** - * Returns the raw JSON value of [outputCostPerSecond]. - * - * Unlike [outputCostPerSecond], this method doesn't throw if the JSON field has an - * unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("output_cost_per_second") - @ExcludeMissing - fun _outputCostPerSecond(): JsonField = outputCostPerSecond + fun maxBudget(): Optional = maxBudget.getOptional("max_budget") /** - * Returns the raw JSON value of [outputCostPerToken]. - * - * Unlike [outputCostPerToken], this method doesn't throw if the JSON field has an - * unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("output_cost_per_token") - @ExcludeMissing - fun _outputCostPerToken(): JsonField = outputCostPerToken + fun maxFileSizeMb(): Optional = maxFileSizeMb.getOptional("max_file_size_mb") /** - * Returns the raw JSON value of [regionName]. - * - * Unlike [regionName], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("region_name") - @ExcludeMissing - fun _regionName(): JsonField = regionName + fun maxRetries(): Optional = maxRetries.getOptional("max_retries") /** - * Returns the raw JSON value of [rpm]. - * - * Unlike [rpm], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("rpm") @ExcludeMissing fun _rpm(): JsonField = rpm + fun mergeReasoningContentInChoices(): Optional = + mergeReasoningContentInChoices.getOptional("merge_reasoning_content_in_choices") /** - * Returns the raw JSON value of [streamTimeout]. - * - * Unlike [streamTimeout], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("stream_timeout") - @ExcludeMissing - fun _streamTimeout(): JsonField = streamTimeout + fun milvusTextField(): Optional = milvusTextField.getOptional("milvus_text_field") /** - * Returns the raw JSON value of [timeout]. - * - * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + fun mockResponse(): Optional = mockResponse.getOptional("mock_response") /** - * Returns the raw JSON value of [tpm]. - * - * Unlike [tpm], this method doesn't throw if the JSON field has an unexpected type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("tpm") @ExcludeMissing fun _tpm(): JsonField = tpm + fun modelInfo(): Optional = modelInfo.getOptional("model_info") /** - * Returns the raw JSON value of [useInPassThrough]. - * - * Unlike [useInPassThrough], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("use_in_pass_through") - @ExcludeMissing - fun _useInPassThrough(): JsonField = useInPassThrough + fun organization(): Optional = organization.getOptional("organization") /** - * Returns the raw JSON value of [vertexCredentials]. - * - * Unlike [vertexCredentials], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("vertex_credentials") - @ExcludeMissing - fun _vertexCredentials(): JsonField = vertexCredentials + fun outputCostPerAudioPerSecond(): Optional = + outputCostPerAudioPerSecond.getOptional("output_cost_per_audio_per_second") /** - * Returns the raw JSON value of [vertexLocation]. - * - * Unlike [vertexLocation], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("vertex_location") - @ExcludeMissing - fun _vertexLocation(): JsonField = vertexLocation + fun outputCostPerAudioToken(): Optional = + outputCostPerAudioToken.getOptional("output_cost_per_audio_token") /** - * Returns the raw JSON value of [vertexProject]. - * - * Unlike [vertexProject], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("vertex_project") - @ExcludeMissing - fun _vertexProject(): JsonField = vertexProject + fun outputCostPerCharacter(): Optional = + outputCostPerCharacter.getOptional("output_cost_per_character") /** - * Returns the raw JSON value of [watsonxRegionName]. - * - * Unlike [watsonxRegionName], this method doesn't throw if the JSON field has an unexpected - * type. + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - @JsonProperty("watsonx_region_name") - @ExcludeMissing - fun _watsonxRegionName(): JsonField = watsonxRegionName + fun outputCostPerCharacterAbove128kTokens(): Optional = + outputCostPerCharacterAbove128kTokens.getOptional( + "output_cost_per_character_above_128k_tokens" + ) - @JsonAnySetter - private fun putAdditionalProperty(key: String, value: JsonValue) { - additionalProperties.put(key, value) - } + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerImage(): Optional = + outputCostPerImage.getOptional("output_cost_per_image") - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = - Collections.unmodifiableMap(additionalProperties) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerImageToken(): Optional = + outputCostPerImageToken.getOptional("output_cost_per_image_token") - fun toBuilder() = Builder().from(this) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerPixel(): Optional = + outputCostPerPixel.getOptional("output_cost_per_pixel") - companion object { + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerReasoningToken(): Optional = + outputCostPerReasoningToken.getOptional("output_cost_per_reasoning_token") - /** - * Returns a mutable builder for constructing an instance of [LlmParams]. - * - * The following fields are required: - * ```java - * .model() - * ``` - */ - @JvmStatic fun builder() = Builder() - } + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerSecond(): Optional = + outputCostPerSecond.getOptional("output_cost_per_second") - /** A builder for [LlmParams]. */ - class Builder internal constructor() { + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerToken(): Optional = + outputCostPerToken.getOptional("output_cost_per_token") - private var model: JsonField? = null - private var apiBase: JsonField = JsonMissing.of() - private var apiKey: JsonField = JsonMissing.of() - private var apiVersion: JsonField = JsonMissing.of() - private var awsAccessKeyId: JsonField = JsonMissing.of() - private var awsRegionName: JsonField = JsonMissing.of() - private var awsSecretAccessKey: JsonField = JsonMissing.of() - private var budgetDuration: JsonField = JsonMissing.of() - private var configurableClientsideAuthParams: - JsonField>? = - null - private var customLlmProvider: JsonField = JsonMissing.of() - private var inputCostPerSecond: JsonField = JsonMissing.of() - private var inputCostPerToken: JsonField = JsonMissing.of() - private var llmTraceId: JsonField = JsonMissing.of() - private var maxBudget: JsonField = JsonMissing.of() - private var maxFileSizeMb: JsonField = JsonMissing.of() - private var maxRetries: JsonField = JsonMissing.of() - private var mergeReasoningContentInChoices: JsonField = JsonMissing.of() - private var modelInfo: JsonValue = JsonMissing.of() - private var organization: JsonField = JsonMissing.of() - private var outputCostPerSecond: JsonField = JsonMissing.of() - private var outputCostPerToken: JsonField = JsonMissing.of() - private var regionName: JsonField = JsonMissing.of() - private var rpm: JsonField = JsonMissing.of() - private var streamTimeout: JsonField = JsonMissing.of() - private var timeout: JsonField = JsonMissing.of() - private var tpm: JsonField = JsonMissing.of() - private var useInPassThrough: JsonField = JsonMissing.of() - private var vertexCredentials: JsonField = JsonMissing.of() - private var vertexLocation: JsonField = JsonMissing.of() - private var vertexProject: JsonField = JsonMissing.of() - private var watsonxRegionName: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerTokenAbove128kTokens(): Optional = + outputCostPerTokenAbove128kTokens.getOptional("output_cost_per_token_above_128k_tokens") - @JvmSynthetic - internal fun from(llmParams: LlmParams) = apply { - model = llmParams.model - apiBase = llmParams.apiBase - apiKey = llmParams.apiKey - apiVersion = llmParams.apiVersion - awsAccessKeyId = llmParams.awsAccessKeyId - awsRegionName = llmParams.awsRegionName - awsSecretAccessKey = llmParams.awsSecretAccessKey - budgetDuration = llmParams.budgetDuration - configurableClientsideAuthParams = - llmParams.configurableClientsideAuthParams.map { it.toMutableList() } - customLlmProvider = llmParams.customLlmProvider - inputCostPerSecond = llmParams.inputCostPerSecond - inputCostPerToken = llmParams.inputCostPerToken - llmTraceId = llmParams.llmTraceId - maxBudget = llmParams.maxBudget - maxFileSizeMb = llmParams.maxFileSizeMb - maxRetries = llmParams.maxRetries - mergeReasoningContentInChoices = llmParams.mergeReasoningContentInChoices - modelInfo = llmParams.modelInfo - organization = llmParams.organization - outputCostPerSecond = llmParams.outputCostPerSecond - outputCostPerToken = llmParams.outputCostPerToken - regionName = llmParams.regionName - rpm = llmParams.rpm - streamTimeout = llmParams.streamTimeout - timeout = llmParams.timeout - tpm = llmParams.tpm - useInPassThrough = llmParams.useInPassThrough - vertexCredentials = llmParams.vertexCredentials - vertexLocation = llmParams.vertexLocation - vertexProject = llmParams.vertexProject - watsonxRegionName = llmParams.watsonxRegionName - additionalProperties = llmParams.additionalProperties.toMutableMap() - } + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerTokenAbove200kTokens(): Optional = + outputCostPerTokenAbove200kTokens.getOptional("output_cost_per_token_above_200k_tokens") - fun model(model: String) = model(JsonField.of(model)) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerTokenBatches(): Optional = + outputCostPerTokenBatches.getOptional("output_cost_per_token_batches") - /** - * Sets [Builder.model] to an arbitrary JSON value. - * - * You should usually call [Builder.model] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun model(model: JsonField) = apply { this.model = model } + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerTokenFlex(): Optional = + outputCostPerTokenFlex.getOptional("output_cost_per_token_flex") - fun apiBase(apiBase: String?) = apiBase(JsonField.ofNullable(apiBase)) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerTokenPriority(): Optional = + outputCostPerTokenPriority.getOptional("output_cost_per_token_priority") - /** Alias for calling [Builder.apiBase] with `apiBase.orElse(null)`. */ - fun apiBase(apiBase: Optional) = apiBase(apiBase.getOrNull()) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun outputCostPerVideoPerSecond(): Optional = + outputCostPerVideoPerSecond.getOptional("output_cost_per_video_per_second") - /** - * Sets [Builder.apiBase] to an arbitrary JSON value. - * - * You should usually call [Builder.apiBase] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun apiBase(apiBase: JsonField) = apply { this.apiBase = apiBase } + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun regionName(): Optional = regionName.getOptional("region_name") - fun apiKey(apiKey: String?) = apiKey(JsonField.ofNullable(apiKey)) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rpm(): Optional = rpm.getOptional("rpm") - /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ - fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun s3BucketName(): Optional = s3BucketName.getOptional("s3_bucket_name") - /** - * Sets [Builder.apiKey] to an arbitrary JSON value. - * - * You should usually call [Builder.apiKey] with a well-typed [String] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun apiKey(apiKey: JsonField) = apply { this.apiKey = apiKey } + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun s3EncryptionKeyId(): Optional = + s3EncryptionKeyId.getOptional("s3_encryption_key_id") - fun apiVersion(apiVersion: String?) = apiVersion(JsonField.ofNullable(apiVersion)) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun searchContextCostPerQuery(): Optional = + searchContextCostPerQuery.getOptional("search_context_cost_per_query") - /** Alias for calling [Builder.apiVersion] with `apiVersion.orElse(null)`. */ + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun streamTimeout(): Optional = streamTimeout.getOptional("stream_timeout") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tieredPricing(): Optional> = + tieredPricing.getOptional("tiered_pricing") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = timeout.getOptional("timeout") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tpm(): Optional = tpm.getOptional("tpm") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun useInPassThrough(): Optional = + useInPassThrough.getOptional("use_in_pass_through") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun useLitellmProxy(): Optional = useLitellmProxy.getOptional("use_litellm_proxy") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun vectorStoreId(): Optional = vectorStoreId.getOptional("vector_store_id") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun vertexCredentials(): Optional = + vertexCredentials.getOptional("vertex_credentials") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun vertexLocation(): Optional = vertexLocation.getOptional("vertex_location") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun vertexProject(): Optional = vertexProject.getOptional("vertex_project") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun watsonxRegionName(): Optional = + watsonxRegionName.getOptional("watsonx_region_name") + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + /** + * Returns the raw JSON value of [apiBase]. + * + * Unlike [apiBase], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_base") @ExcludeMissing fun _apiBase(): JsonField = apiBase + + /** + * Returns the raw JSON value of [apiKey]. + * + * Unlike [apiKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_key") @ExcludeMissing fun _apiKey(): JsonField = apiKey + + /** + * Returns the raw JSON value of [apiVersion]. + * + * Unlike [apiVersion], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_version") + @ExcludeMissing + fun _apiVersion(): JsonField = apiVersion + + /** + * Returns the raw JSON value of [autoRouterConfig]. + * + * Unlike [autoRouterConfig], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auto_router_config") + @ExcludeMissing + fun _autoRouterConfig(): JsonField = autoRouterConfig + + /** + * Returns the raw JSON value of [autoRouterConfigPath]. + * + * Unlike [autoRouterConfigPath], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auto_router_config_path") + @ExcludeMissing + fun _autoRouterConfigPath(): JsonField = autoRouterConfigPath + + /** + * Returns the raw JSON value of [autoRouterDefaultModel]. + * + * Unlike [autoRouterDefaultModel], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auto_router_default_model") + @ExcludeMissing + fun _autoRouterDefaultModel(): JsonField = autoRouterDefaultModel + + /** + * Returns the raw JSON value of [autoRouterEmbeddingModel]. + * + * Unlike [autoRouterEmbeddingModel], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auto_router_embedding_model") + @ExcludeMissing + fun _autoRouterEmbeddingModel(): JsonField = autoRouterEmbeddingModel + + /** + * Returns the raw JSON value of [awsAccessKeyId]. + * + * Unlike [awsAccessKeyId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("aws_access_key_id") + @ExcludeMissing + fun _awsAccessKeyId(): JsonField = awsAccessKeyId + + /** + * Returns the raw JSON value of [awsBedrockRuntimeEndpoint]. + * + * Unlike [awsBedrockRuntimeEndpoint], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("aws_bedrock_runtime_endpoint") + @ExcludeMissing + fun _awsBedrockRuntimeEndpoint(): JsonField = awsBedrockRuntimeEndpoint + + /** + * Returns the raw JSON value of [awsRegionName]. + * + * Unlike [awsRegionName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("aws_region_name") + @ExcludeMissing + fun _awsRegionName(): JsonField = awsRegionName + + /** + * Returns the raw JSON value of [awsSecretAccessKey]. + * + * Unlike [awsSecretAccessKey], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("aws_secret_access_key") + @ExcludeMissing + fun _awsSecretAccessKey(): JsonField = awsSecretAccessKey + + /** + * Returns the raw JSON value of [budgetDuration]. + * + * Unlike [budgetDuration], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("budget_duration") + @ExcludeMissing + fun _budgetDuration(): JsonField = budgetDuration + + /** + * Returns the raw JSON value of [cacheCreationInputAudioTokenCost]. + * + * Unlike [cacheCreationInputAudioTokenCost], this method doesn't throw if the JSON field + * has an unexpected type. + */ + @JsonProperty("cache_creation_input_audio_token_cost") + @ExcludeMissing + fun _cacheCreationInputAudioTokenCost(): JsonField = + cacheCreationInputAudioTokenCost + + /** + * Returns the raw JSON value of [cacheCreationInputTokenCost]. + * + * Unlike [cacheCreationInputTokenCost], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_creation_input_token_cost") + @ExcludeMissing + fun _cacheCreationInputTokenCost(): JsonField = cacheCreationInputTokenCost + + /** + * Returns the raw JSON value of [cacheCreationInputTokenCostAbove1hr]. + * + * Unlike [cacheCreationInputTokenCostAbove1hr], this method doesn't throw if the JSON field + * has an unexpected type. + */ + @JsonProperty("cache_creation_input_token_cost_above_1hr") + @ExcludeMissing + fun _cacheCreationInputTokenCostAbove1hr(): JsonField = + cacheCreationInputTokenCostAbove1hr + + /** + * Returns the raw JSON value of [cacheCreationInputTokenCostAbove200kTokens]. + * + * Unlike [cacheCreationInputTokenCostAbove200kTokens], this method doesn't throw if the + * JSON field has an unexpected type. + */ + @JsonProperty("cache_creation_input_token_cost_above_200k_tokens") + @ExcludeMissing + fun _cacheCreationInputTokenCostAbove200kTokens(): JsonField = + cacheCreationInputTokenCostAbove200kTokens + + /** + * Returns the raw JSON value of [cacheReadInputAudioTokenCost]. + * + * Unlike [cacheReadInputAudioTokenCost], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_read_input_audio_token_cost") + @ExcludeMissing + fun _cacheReadInputAudioTokenCost(): JsonField = cacheReadInputAudioTokenCost + + /** + * Returns the raw JSON value of [cacheReadInputTokenCost]. + * + * Unlike [cacheReadInputTokenCost], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_read_input_token_cost") + @ExcludeMissing + fun _cacheReadInputTokenCost(): JsonField = cacheReadInputTokenCost + + /** + * Returns the raw JSON value of [cacheReadInputTokenCostAbove200kTokens]. + * + * Unlike [cacheReadInputTokenCostAbove200kTokens], this method doesn't throw if the JSON + * field has an unexpected type. + */ + @JsonProperty("cache_read_input_token_cost_above_200k_tokens") + @ExcludeMissing + fun _cacheReadInputTokenCostAbove200kTokens(): JsonField = + cacheReadInputTokenCostAbove200kTokens + + /** + * Returns the raw JSON value of [cacheReadInputTokenCostFlex]. + * + * Unlike [cacheReadInputTokenCostFlex], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("cache_read_input_token_cost_flex") + @ExcludeMissing + fun _cacheReadInputTokenCostFlex(): JsonField = cacheReadInputTokenCostFlex + + /** + * Returns the raw JSON value of [cacheReadInputTokenCostPriority]. + * + * Unlike [cacheReadInputTokenCostPriority], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("cache_read_input_token_cost_priority") + @ExcludeMissing + fun _cacheReadInputTokenCostPriority(): JsonField = cacheReadInputTokenCostPriority + + /** + * Returns the raw JSON value of [citationCostPerToken]. + * + * Unlike [citationCostPerToken], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("citation_cost_per_token") + @ExcludeMissing + fun _citationCostPerToken(): JsonField = citationCostPerToken + + /** + * Returns the raw JSON value of [configurableClientsideAuthParams]. + * + * Unlike [configurableClientsideAuthParams], this method doesn't throw if the JSON field + * has an unexpected type. + */ + @JsonProperty("configurable_clientside_auth_params") + @ExcludeMissing + fun _configurableClientsideAuthParams(): JsonField> = + configurableClientsideAuthParams + + /** + * Returns the raw JSON value of [customLlmProvider]. + * + * Unlike [customLlmProvider], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("custom_llm_provider") + @ExcludeMissing + fun _customLlmProvider(): JsonField = customLlmProvider + + /** + * Returns the raw JSON value of [gcsBucketName]. + * + * Unlike [gcsBucketName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("gcs_bucket_name") + @ExcludeMissing + fun _gcsBucketName(): JsonField = gcsBucketName + + /** + * Returns the raw JSON value of [inputCostPerAudioPerSecond]. + * + * Unlike [inputCostPerAudioPerSecond], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("input_cost_per_audio_per_second") + @ExcludeMissing + fun _inputCostPerAudioPerSecond(): JsonField = inputCostPerAudioPerSecond + + /** + * Returns the raw JSON value of [inputCostPerAudioPerSecondAbove128kTokens]. + * + * Unlike [inputCostPerAudioPerSecondAbove128kTokens], this method doesn't throw if the JSON + * field has an unexpected type. + */ + @JsonProperty("input_cost_per_audio_per_second_above_128k_tokens") + @ExcludeMissing + fun _inputCostPerAudioPerSecondAbove128kTokens(): JsonField = + inputCostPerAudioPerSecondAbove128kTokens + + /** + * Returns the raw JSON value of [inputCostPerAudioToken]. + * + * Unlike [inputCostPerAudioToken], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("input_cost_per_audio_token") + @ExcludeMissing + fun _inputCostPerAudioToken(): JsonField = inputCostPerAudioToken + + /** + * Returns the raw JSON value of [inputCostPerCharacter]. + * + * Unlike [inputCostPerCharacter], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("input_cost_per_character") + @ExcludeMissing + fun _inputCostPerCharacter(): JsonField = inputCostPerCharacter + + /** + * Returns the raw JSON value of [inputCostPerCharacterAbove128kTokens]. + * + * Unlike [inputCostPerCharacterAbove128kTokens], this method doesn't throw if the JSON + * field has an unexpected type. + */ + @JsonProperty("input_cost_per_character_above_128k_tokens") + @ExcludeMissing + fun _inputCostPerCharacterAbove128kTokens(): JsonField = + inputCostPerCharacterAbove128kTokens + + /** + * Returns the raw JSON value of [inputCostPerImage]. + * + * Unlike [inputCostPerImage], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("input_cost_per_image") + @ExcludeMissing + fun _inputCostPerImage(): JsonField = inputCostPerImage + + /** + * Returns the raw JSON value of [inputCostPerImageAbove128kTokens]. + * + * Unlike [inputCostPerImageAbove128kTokens], this method doesn't throw if the JSON field + * has an unexpected type. + */ + @JsonProperty("input_cost_per_image_above_128k_tokens") + @ExcludeMissing + fun _inputCostPerImageAbove128kTokens(): JsonField = + inputCostPerImageAbove128kTokens + + /** + * Returns the raw JSON value of [inputCostPerPixel]. + * + * Unlike [inputCostPerPixel], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("input_cost_per_pixel") + @ExcludeMissing + fun _inputCostPerPixel(): JsonField = inputCostPerPixel + + /** + * Returns the raw JSON value of [inputCostPerQuery]. + * + * Unlike [inputCostPerQuery], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("input_cost_per_query") + @ExcludeMissing + fun _inputCostPerQuery(): JsonField = inputCostPerQuery + + /** + * Returns the raw JSON value of [inputCostPerSecond]. + * + * Unlike [inputCostPerSecond], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("input_cost_per_second") + @ExcludeMissing + fun _inputCostPerSecond(): JsonField = inputCostPerSecond + + /** + * Returns the raw JSON value of [inputCostPerToken]. + * + * Unlike [inputCostPerToken], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("input_cost_per_token") + @ExcludeMissing + fun _inputCostPerToken(): JsonField = inputCostPerToken + + /** + * Returns the raw JSON value of [inputCostPerTokenAbove128kTokens]. + * + * Unlike [inputCostPerTokenAbove128kTokens], this method doesn't throw if the JSON field + * has an unexpected type. + */ + @JsonProperty("input_cost_per_token_above_128k_tokens") + @ExcludeMissing + fun _inputCostPerTokenAbove128kTokens(): JsonField = + inputCostPerTokenAbove128kTokens + + /** + * Returns the raw JSON value of [inputCostPerTokenAbove200kTokens]. + * + * Unlike [inputCostPerTokenAbove200kTokens], this method doesn't throw if the JSON field + * has an unexpected type. + */ + @JsonProperty("input_cost_per_token_above_200k_tokens") + @ExcludeMissing + fun _inputCostPerTokenAbove200kTokens(): JsonField = + inputCostPerTokenAbove200kTokens + + /** + * Returns the raw JSON value of [inputCostPerTokenBatches]. + * + * Unlike [inputCostPerTokenBatches], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("input_cost_per_token_batches") + @ExcludeMissing + fun _inputCostPerTokenBatches(): JsonField = inputCostPerTokenBatches + + /** + * Returns the raw JSON value of [inputCostPerTokenCacheHit]. + * + * Unlike [inputCostPerTokenCacheHit], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("input_cost_per_token_cache_hit") + @ExcludeMissing + fun _inputCostPerTokenCacheHit(): JsonField = inputCostPerTokenCacheHit + + /** + * Returns the raw JSON value of [inputCostPerTokenFlex]. + * + * Unlike [inputCostPerTokenFlex], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("input_cost_per_token_flex") + @ExcludeMissing + fun _inputCostPerTokenFlex(): JsonField = inputCostPerTokenFlex + + /** + * Returns the raw JSON value of [inputCostPerTokenPriority]. + * + * Unlike [inputCostPerTokenPriority], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("input_cost_per_token_priority") + @ExcludeMissing + fun _inputCostPerTokenPriority(): JsonField = inputCostPerTokenPriority + + /** + * Returns the raw JSON value of [inputCostPerVideoPerSecond]. + * + * Unlike [inputCostPerVideoPerSecond], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("input_cost_per_video_per_second") + @ExcludeMissing + fun _inputCostPerVideoPerSecond(): JsonField = inputCostPerVideoPerSecond + + /** + * Returns the raw JSON value of [inputCostPerVideoPerSecondAbove128kTokens]. + * + * Unlike [inputCostPerVideoPerSecondAbove128kTokens], this method doesn't throw if the JSON + * field has an unexpected type. + */ + @JsonProperty("input_cost_per_video_per_second_above_128k_tokens") + @ExcludeMissing + fun _inputCostPerVideoPerSecondAbove128kTokens(): JsonField = + inputCostPerVideoPerSecondAbove128kTokens + + /** + * Returns the raw JSON value of [inputCostPerVideoPerSecondAbove15sInterval]. + * + * Unlike [inputCostPerVideoPerSecondAbove15sInterval], this method doesn't throw if the + * JSON field has an unexpected type. + */ + @JsonProperty("input_cost_per_video_per_second_above_15s_interval") + @ExcludeMissing + fun _inputCostPerVideoPerSecondAbove15sInterval(): JsonField = + inputCostPerVideoPerSecondAbove15sInterval + + /** + * Returns the raw JSON value of [inputCostPerVideoPerSecondAbove8sInterval]. + * + * Unlike [inputCostPerVideoPerSecondAbove8sInterval], this method doesn't throw if the JSON + * field has an unexpected type. + */ + @JsonProperty("input_cost_per_video_per_second_above_8s_interval") + @ExcludeMissing + fun _inputCostPerVideoPerSecondAbove8sInterval(): JsonField = + inputCostPerVideoPerSecondAbove8sInterval + + /** + * Returns the raw JSON value of [litellmCredentialName]. + * + * Unlike [litellmCredentialName], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("litellm_credential_name") + @ExcludeMissing + fun _litellmCredentialName(): JsonField = litellmCredentialName + + /** + * Returns the raw JSON value of [litellmTraceId]. + * + * Unlike [litellmTraceId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("litellm_trace_id") + @ExcludeMissing + fun _litellmTraceId(): JsonField = litellmTraceId + + /** + * Returns the raw JSON value of [maxBudget]. + * + * Unlike [maxBudget], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("max_budget") @ExcludeMissing fun _maxBudget(): JsonField = maxBudget + + /** + * Returns the raw JSON value of [maxFileSizeMb]. + * + * Unlike [maxFileSizeMb], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("max_file_size_mb") + @ExcludeMissing + fun _maxFileSizeMb(): JsonField = maxFileSizeMb + + /** + * Returns the raw JSON value of [maxRetries]. + * + * Unlike [maxRetries], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("max_retries") @ExcludeMissing fun _maxRetries(): JsonField = maxRetries + + /** + * Returns the raw JSON value of [mergeReasoningContentInChoices]. + * + * Unlike [mergeReasoningContentInChoices], this method doesn't throw if the JSON field has + * an unexpected type. + */ + @JsonProperty("merge_reasoning_content_in_choices") + @ExcludeMissing + fun _mergeReasoningContentInChoices(): JsonField = mergeReasoningContentInChoices + + /** + * Returns the raw JSON value of [milvusTextField]. + * + * Unlike [milvusTextField], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("milvus_text_field") + @ExcludeMissing + fun _milvusTextField(): JsonField = milvusTextField + + /** + * Returns the raw JSON value of [mockResponse]. + * + * Unlike [mockResponse], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("mock_response") + @ExcludeMissing + fun _mockResponse(): JsonField = mockResponse + + /** + * Returns the raw JSON value of [modelInfo]. + * + * Unlike [modelInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model_info") + @ExcludeMissing + fun _modelInfo(): JsonField = modelInfo + + /** + * Returns the raw JSON value of [organization]. + * + * Unlike [organization], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("organization") + @ExcludeMissing + fun _organization(): JsonField = organization + + /** + * Returns the raw JSON value of [outputCostPerAudioPerSecond]. + * + * Unlike [outputCostPerAudioPerSecond], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_audio_per_second") + @ExcludeMissing + fun _outputCostPerAudioPerSecond(): JsonField = outputCostPerAudioPerSecond + + /** + * Returns the raw JSON value of [outputCostPerAudioToken]. + * + * Unlike [outputCostPerAudioToken], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_audio_token") + @ExcludeMissing + fun _outputCostPerAudioToken(): JsonField = outputCostPerAudioToken + + /** + * Returns the raw JSON value of [outputCostPerCharacter]. + * + * Unlike [outputCostPerCharacter], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_character") + @ExcludeMissing + fun _outputCostPerCharacter(): JsonField = outputCostPerCharacter + + /** + * Returns the raw JSON value of [outputCostPerCharacterAbove128kTokens]. + * + * Unlike [outputCostPerCharacterAbove128kTokens], this method doesn't throw if the JSON + * field has an unexpected type. + */ + @JsonProperty("output_cost_per_character_above_128k_tokens") + @ExcludeMissing + fun _outputCostPerCharacterAbove128kTokens(): JsonField = + outputCostPerCharacterAbove128kTokens + + /** + * Returns the raw JSON value of [outputCostPerImage]. + * + * Unlike [outputCostPerImage], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_image") + @ExcludeMissing + fun _outputCostPerImage(): JsonField = outputCostPerImage + + /** + * Returns the raw JSON value of [outputCostPerImageToken]. + * + * Unlike [outputCostPerImageToken], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_image_token") + @ExcludeMissing + fun _outputCostPerImageToken(): JsonField = outputCostPerImageToken + + /** + * Returns the raw JSON value of [outputCostPerPixel]. + * + * Unlike [outputCostPerPixel], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_pixel") + @ExcludeMissing + fun _outputCostPerPixel(): JsonField = outputCostPerPixel + + /** + * Returns the raw JSON value of [outputCostPerReasoningToken]. + * + * Unlike [outputCostPerReasoningToken], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_reasoning_token") + @ExcludeMissing + fun _outputCostPerReasoningToken(): JsonField = outputCostPerReasoningToken + + /** + * Returns the raw JSON value of [outputCostPerSecond]. + * + * Unlike [outputCostPerSecond], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_second") + @ExcludeMissing + fun _outputCostPerSecond(): JsonField = outputCostPerSecond + + /** + * Returns the raw JSON value of [outputCostPerToken]. + * + * Unlike [outputCostPerToken], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_token") + @ExcludeMissing + fun _outputCostPerToken(): JsonField = outputCostPerToken + + /** + * Returns the raw JSON value of [outputCostPerTokenAbove128kTokens]. + * + * Unlike [outputCostPerTokenAbove128kTokens], this method doesn't throw if the JSON field + * has an unexpected type. + */ + @JsonProperty("output_cost_per_token_above_128k_tokens") + @ExcludeMissing + fun _outputCostPerTokenAbove128kTokens(): JsonField = + outputCostPerTokenAbove128kTokens + + /** + * Returns the raw JSON value of [outputCostPerTokenAbove200kTokens]. + * + * Unlike [outputCostPerTokenAbove200kTokens], this method doesn't throw if the JSON field + * has an unexpected type. + */ + @JsonProperty("output_cost_per_token_above_200k_tokens") + @ExcludeMissing + fun _outputCostPerTokenAbove200kTokens(): JsonField = + outputCostPerTokenAbove200kTokens + + /** + * Returns the raw JSON value of [outputCostPerTokenBatches]. + * + * Unlike [outputCostPerTokenBatches], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_token_batches") + @ExcludeMissing + fun _outputCostPerTokenBatches(): JsonField = outputCostPerTokenBatches + + /** + * Returns the raw JSON value of [outputCostPerTokenFlex]. + * + * Unlike [outputCostPerTokenFlex], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_token_flex") + @ExcludeMissing + fun _outputCostPerTokenFlex(): JsonField = outputCostPerTokenFlex + + /** + * Returns the raw JSON value of [outputCostPerTokenPriority]. + * + * Unlike [outputCostPerTokenPriority], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_token_priority") + @ExcludeMissing + fun _outputCostPerTokenPriority(): JsonField = outputCostPerTokenPriority + + /** + * Returns the raw JSON value of [outputCostPerVideoPerSecond]. + * + * Unlike [outputCostPerVideoPerSecond], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("output_cost_per_video_per_second") + @ExcludeMissing + fun _outputCostPerVideoPerSecond(): JsonField = outputCostPerVideoPerSecond + + /** + * Returns the raw JSON value of [regionName]. + * + * Unlike [regionName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("region_name") + @ExcludeMissing + fun _regionName(): JsonField = regionName + + /** + * Returns the raw JSON value of [rpm]. + * + * Unlike [rpm], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("rpm") @ExcludeMissing fun _rpm(): JsonField = rpm + + /** + * Returns the raw JSON value of [s3BucketName]. + * + * Unlike [s3BucketName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("s3_bucket_name") + @ExcludeMissing + fun _s3BucketName(): JsonField = s3BucketName + + /** + * Returns the raw JSON value of [s3EncryptionKeyId]. + * + * Unlike [s3EncryptionKeyId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("s3_encryption_key_id") + @ExcludeMissing + fun _s3EncryptionKeyId(): JsonField = s3EncryptionKeyId + + /** + * Returns the raw JSON value of [searchContextCostPerQuery]. + * + * Unlike [searchContextCostPerQuery], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("search_context_cost_per_query") + @ExcludeMissing + fun _searchContextCostPerQuery(): JsonField = + searchContextCostPerQuery + + /** + * Returns the raw JSON value of [streamTimeout]. + * + * Unlike [streamTimeout], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("stream_timeout") + @ExcludeMissing + fun _streamTimeout(): JsonField = streamTimeout + + /** + * Returns the raw JSON value of [tieredPricing]. + * + * Unlike [tieredPricing], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tiered_pricing") + @ExcludeMissing + fun _tieredPricing(): JsonField> = tieredPricing + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + /** + * Returns the raw JSON value of [tpm]. + * + * Unlike [tpm], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tpm") @ExcludeMissing fun _tpm(): JsonField = tpm + + /** + * Returns the raw JSON value of [useInPassThrough]. + * + * Unlike [useInPassThrough], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("use_in_pass_through") + @ExcludeMissing + fun _useInPassThrough(): JsonField = useInPassThrough + + /** + * Returns the raw JSON value of [useLitellmProxy]. + * + * Unlike [useLitellmProxy], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("use_litellm_proxy") + @ExcludeMissing + fun _useLitellmProxy(): JsonField = useLitellmProxy + + /** + * Returns the raw JSON value of [vectorStoreId]. + * + * Unlike [vectorStoreId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("vector_store_id") + @ExcludeMissing + fun _vectorStoreId(): JsonField = vectorStoreId + + /** + * Returns the raw JSON value of [vertexCredentials]. + * + * Unlike [vertexCredentials], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("vertex_credentials") + @ExcludeMissing + fun _vertexCredentials(): JsonField = vertexCredentials + + /** + * Returns the raw JSON value of [vertexLocation]. + * + * Unlike [vertexLocation], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("vertex_location") + @ExcludeMissing + fun _vertexLocation(): JsonField = vertexLocation + + /** + * Returns the raw JSON value of [vertexProject]. + * + * Unlike [vertexProject], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("vertex_project") + @ExcludeMissing + fun _vertexProject(): JsonField = vertexProject + + /** + * Returns the raw JSON value of [watsonxRegionName]. + * + * Unlike [watsonxRegionName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("watsonx_region_name") + @ExcludeMissing + fun _watsonxRegionName(): JsonField = watsonxRegionName + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [LitellmParams]. + * + * The following fields are required: + * ```java + * .model() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LitellmParams]. */ + class Builder internal constructor() { + + private var model: JsonField? = null + private var apiBase: JsonField = JsonMissing.of() + private var apiKey: JsonField = JsonMissing.of() + private var apiVersion: JsonField = JsonMissing.of() + private var autoRouterConfig: JsonField = JsonMissing.of() + private var autoRouterConfigPath: JsonField = JsonMissing.of() + private var autoRouterDefaultModel: JsonField = JsonMissing.of() + private var autoRouterEmbeddingModel: JsonField = JsonMissing.of() + private var awsAccessKeyId: JsonField = JsonMissing.of() + private var awsBedrockRuntimeEndpoint: JsonField = JsonMissing.of() + private var awsRegionName: JsonField = JsonMissing.of() + private var awsSecretAccessKey: JsonField = JsonMissing.of() + private var budgetDuration: JsonField = JsonMissing.of() + private var cacheCreationInputAudioTokenCost: JsonField = JsonMissing.of() + private var cacheCreationInputTokenCost: JsonField = JsonMissing.of() + private var cacheCreationInputTokenCostAbove1hr: JsonField = JsonMissing.of() + private var cacheCreationInputTokenCostAbove200kTokens: JsonField = + JsonMissing.of() + private var cacheReadInputAudioTokenCost: JsonField = JsonMissing.of() + private var cacheReadInputTokenCost: JsonField = JsonMissing.of() + private var cacheReadInputTokenCostAbove200kTokens: JsonField = JsonMissing.of() + private var cacheReadInputTokenCostFlex: JsonField = JsonMissing.of() + private var cacheReadInputTokenCostPriority: JsonField = JsonMissing.of() + private var citationCostPerToken: JsonField = JsonMissing.of() + private var configurableClientsideAuthParams: + JsonField>? = + null + private var customLlmProvider: JsonField = JsonMissing.of() + private var gcsBucketName: JsonField = JsonMissing.of() + private var inputCostPerAudioPerSecond: JsonField = JsonMissing.of() + private var inputCostPerAudioPerSecondAbove128kTokens: JsonField = + JsonMissing.of() + private var inputCostPerAudioToken: JsonField = JsonMissing.of() + private var inputCostPerCharacter: JsonField = JsonMissing.of() + private var inputCostPerCharacterAbove128kTokens: JsonField = JsonMissing.of() + private var inputCostPerImage: JsonField = JsonMissing.of() + private var inputCostPerImageAbove128kTokens: JsonField = JsonMissing.of() + private var inputCostPerPixel: JsonField = JsonMissing.of() + private var inputCostPerQuery: JsonField = JsonMissing.of() + private var inputCostPerSecond: JsonField = JsonMissing.of() + private var inputCostPerToken: JsonField = JsonMissing.of() + private var inputCostPerTokenAbove128kTokens: JsonField = JsonMissing.of() + private var inputCostPerTokenAbove200kTokens: JsonField = JsonMissing.of() + private var inputCostPerTokenBatches: JsonField = JsonMissing.of() + private var inputCostPerTokenCacheHit: JsonField = JsonMissing.of() + private var inputCostPerTokenFlex: JsonField = JsonMissing.of() + private var inputCostPerTokenPriority: JsonField = JsonMissing.of() + private var inputCostPerVideoPerSecond: JsonField = JsonMissing.of() + private var inputCostPerVideoPerSecondAbove128kTokens: JsonField = + JsonMissing.of() + private var inputCostPerVideoPerSecondAbove15sInterval: JsonField = + JsonMissing.of() + private var inputCostPerVideoPerSecondAbove8sInterval: JsonField = + JsonMissing.of() + private var litellmCredentialName: JsonField = JsonMissing.of() + private var litellmTraceId: JsonField = JsonMissing.of() + private var maxBudget: JsonField = JsonMissing.of() + private var maxFileSizeMb: JsonField = JsonMissing.of() + private var maxRetries: JsonField = JsonMissing.of() + private var mergeReasoningContentInChoices: JsonField = JsonMissing.of() + private var milvusTextField: JsonField = JsonMissing.of() + private var mockResponse: JsonField = JsonMissing.of() + private var modelInfo: JsonField = JsonMissing.of() + private var organization: JsonField = JsonMissing.of() + private var outputCostPerAudioPerSecond: JsonField = JsonMissing.of() + private var outputCostPerAudioToken: JsonField = JsonMissing.of() + private var outputCostPerCharacter: JsonField = JsonMissing.of() + private var outputCostPerCharacterAbove128kTokens: JsonField = JsonMissing.of() + private var outputCostPerImage: JsonField = JsonMissing.of() + private var outputCostPerImageToken: JsonField = JsonMissing.of() + private var outputCostPerPixel: JsonField = JsonMissing.of() + private var outputCostPerReasoningToken: JsonField = JsonMissing.of() + private var outputCostPerSecond: JsonField = JsonMissing.of() + private var outputCostPerToken: JsonField = JsonMissing.of() + private var outputCostPerTokenAbove128kTokens: JsonField = JsonMissing.of() + private var outputCostPerTokenAbove200kTokens: JsonField = JsonMissing.of() + private var outputCostPerTokenBatches: JsonField = JsonMissing.of() + private var outputCostPerTokenFlex: JsonField = JsonMissing.of() + private var outputCostPerTokenPriority: JsonField = JsonMissing.of() + private var outputCostPerVideoPerSecond: JsonField = JsonMissing.of() + private var regionName: JsonField = JsonMissing.of() + private var rpm: JsonField = JsonMissing.of() + private var s3BucketName: JsonField = JsonMissing.of() + private var s3EncryptionKeyId: JsonField = JsonMissing.of() + private var searchContextCostPerQuery: JsonField = + JsonMissing.of() + private var streamTimeout: JsonField = JsonMissing.of() + private var tieredPricing: JsonField>? = null + private var timeout: JsonField = JsonMissing.of() + private var tpm: JsonField = JsonMissing.of() + private var useInPassThrough: JsonField = JsonMissing.of() + private var useLitellmProxy: JsonField = JsonMissing.of() + private var vectorStoreId: JsonField = JsonMissing.of() + private var vertexCredentials: JsonField = JsonMissing.of() + private var vertexLocation: JsonField = JsonMissing.of() + private var vertexProject: JsonField = JsonMissing.of() + private var watsonxRegionName: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(litellmParams: LitellmParams) = apply { + model = litellmParams.model + apiBase = litellmParams.apiBase + apiKey = litellmParams.apiKey + apiVersion = litellmParams.apiVersion + autoRouterConfig = litellmParams.autoRouterConfig + autoRouterConfigPath = litellmParams.autoRouterConfigPath + autoRouterDefaultModel = litellmParams.autoRouterDefaultModel + autoRouterEmbeddingModel = litellmParams.autoRouterEmbeddingModel + awsAccessKeyId = litellmParams.awsAccessKeyId + awsBedrockRuntimeEndpoint = litellmParams.awsBedrockRuntimeEndpoint + awsRegionName = litellmParams.awsRegionName + awsSecretAccessKey = litellmParams.awsSecretAccessKey + budgetDuration = litellmParams.budgetDuration + cacheCreationInputAudioTokenCost = litellmParams.cacheCreationInputAudioTokenCost + cacheCreationInputTokenCost = litellmParams.cacheCreationInputTokenCost + cacheCreationInputTokenCostAbove1hr = + litellmParams.cacheCreationInputTokenCostAbove1hr + cacheCreationInputTokenCostAbove200kTokens = + litellmParams.cacheCreationInputTokenCostAbove200kTokens + cacheReadInputAudioTokenCost = litellmParams.cacheReadInputAudioTokenCost + cacheReadInputTokenCost = litellmParams.cacheReadInputTokenCost + cacheReadInputTokenCostAbove200kTokens = + litellmParams.cacheReadInputTokenCostAbove200kTokens + cacheReadInputTokenCostFlex = litellmParams.cacheReadInputTokenCostFlex + cacheReadInputTokenCostPriority = litellmParams.cacheReadInputTokenCostPriority + citationCostPerToken = litellmParams.citationCostPerToken + configurableClientsideAuthParams = + litellmParams.configurableClientsideAuthParams.map { it.toMutableList() } + customLlmProvider = litellmParams.customLlmProvider + gcsBucketName = litellmParams.gcsBucketName + inputCostPerAudioPerSecond = litellmParams.inputCostPerAudioPerSecond + inputCostPerAudioPerSecondAbove128kTokens = + litellmParams.inputCostPerAudioPerSecondAbove128kTokens + inputCostPerAudioToken = litellmParams.inputCostPerAudioToken + inputCostPerCharacter = litellmParams.inputCostPerCharacter + inputCostPerCharacterAbove128kTokens = + litellmParams.inputCostPerCharacterAbove128kTokens + inputCostPerImage = litellmParams.inputCostPerImage + inputCostPerImageAbove128kTokens = litellmParams.inputCostPerImageAbove128kTokens + inputCostPerPixel = litellmParams.inputCostPerPixel + inputCostPerQuery = litellmParams.inputCostPerQuery + inputCostPerSecond = litellmParams.inputCostPerSecond + inputCostPerToken = litellmParams.inputCostPerToken + inputCostPerTokenAbove128kTokens = litellmParams.inputCostPerTokenAbove128kTokens + inputCostPerTokenAbove200kTokens = litellmParams.inputCostPerTokenAbove200kTokens + inputCostPerTokenBatches = litellmParams.inputCostPerTokenBatches + inputCostPerTokenCacheHit = litellmParams.inputCostPerTokenCacheHit + inputCostPerTokenFlex = litellmParams.inputCostPerTokenFlex + inputCostPerTokenPriority = litellmParams.inputCostPerTokenPriority + inputCostPerVideoPerSecond = litellmParams.inputCostPerVideoPerSecond + inputCostPerVideoPerSecondAbove128kTokens = + litellmParams.inputCostPerVideoPerSecondAbove128kTokens + inputCostPerVideoPerSecondAbove15sInterval = + litellmParams.inputCostPerVideoPerSecondAbove15sInterval + inputCostPerVideoPerSecondAbove8sInterval = + litellmParams.inputCostPerVideoPerSecondAbove8sInterval + litellmCredentialName = litellmParams.litellmCredentialName + litellmTraceId = litellmParams.litellmTraceId + maxBudget = litellmParams.maxBudget + maxFileSizeMb = litellmParams.maxFileSizeMb + maxRetries = litellmParams.maxRetries + mergeReasoningContentInChoices = litellmParams.mergeReasoningContentInChoices + milvusTextField = litellmParams.milvusTextField + mockResponse = litellmParams.mockResponse + modelInfo = litellmParams.modelInfo + organization = litellmParams.organization + outputCostPerAudioPerSecond = litellmParams.outputCostPerAudioPerSecond + outputCostPerAudioToken = litellmParams.outputCostPerAudioToken + outputCostPerCharacter = litellmParams.outputCostPerCharacter + outputCostPerCharacterAbove128kTokens = + litellmParams.outputCostPerCharacterAbove128kTokens + outputCostPerImage = litellmParams.outputCostPerImage + outputCostPerImageToken = litellmParams.outputCostPerImageToken + outputCostPerPixel = litellmParams.outputCostPerPixel + outputCostPerReasoningToken = litellmParams.outputCostPerReasoningToken + outputCostPerSecond = litellmParams.outputCostPerSecond + outputCostPerToken = litellmParams.outputCostPerToken + outputCostPerTokenAbove128kTokens = litellmParams.outputCostPerTokenAbove128kTokens + outputCostPerTokenAbove200kTokens = litellmParams.outputCostPerTokenAbove200kTokens + outputCostPerTokenBatches = litellmParams.outputCostPerTokenBatches + outputCostPerTokenFlex = litellmParams.outputCostPerTokenFlex + outputCostPerTokenPriority = litellmParams.outputCostPerTokenPriority + outputCostPerVideoPerSecond = litellmParams.outputCostPerVideoPerSecond + regionName = litellmParams.regionName + rpm = litellmParams.rpm + s3BucketName = litellmParams.s3BucketName + s3EncryptionKeyId = litellmParams.s3EncryptionKeyId + searchContextCostPerQuery = litellmParams.searchContextCostPerQuery + streamTimeout = litellmParams.streamTimeout + tieredPricing = litellmParams.tieredPricing.map { it.toMutableList() } + timeout = litellmParams.timeout + tpm = litellmParams.tpm + useInPassThrough = litellmParams.useInPassThrough + useLitellmProxy = litellmParams.useLitellmProxy + vectorStoreId = litellmParams.vectorStoreId + vertexCredentials = litellmParams.vertexCredentials + vertexLocation = litellmParams.vertexLocation + vertexProject = litellmParams.vertexProject + watsonxRegionName = litellmParams.watsonxRegionName + additionalProperties = litellmParams.additionalProperties.toMutableMap() + } + + fun model(model: String) = model(JsonField.of(model)) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun apiBase(apiBase: String?) = apiBase(JsonField.ofNullable(apiBase)) + + /** Alias for calling [Builder.apiBase] with `apiBase.orElse(null)`. */ + fun apiBase(apiBase: Optional) = apiBase(apiBase.getOrNull()) + + /** + * Sets [Builder.apiBase] to an arbitrary JSON value. + * + * You should usually call [Builder.apiBase] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiBase(apiBase: JsonField) = apply { this.apiBase = apiBase } + + fun apiKey(apiKey: String?) = apiKey(JsonField.ofNullable(apiKey)) + + /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ + fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) + + /** + * Sets [Builder.apiKey] to an arbitrary JSON value. + * + * You should usually call [Builder.apiKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiKey(apiKey: JsonField) = apply { this.apiKey = apiKey } + + fun apiVersion(apiVersion: String?) = apiVersion(JsonField.ofNullable(apiVersion)) + + /** Alias for calling [Builder.apiVersion] with `apiVersion.orElse(null)`. */ fun apiVersion(apiVersion: Optional) = apiVersion(apiVersion.getOrNull()) /** - * Sets [Builder.apiVersion] to an arbitrary JSON value. + * Sets [Builder.apiVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.apiVersion] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun apiVersion(apiVersion: JsonField) = apply { this.apiVersion = apiVersion } + + fun autoRouterConfig(autoRouterConfig: String?) = + autoRouterConfig(JsonField.ofNullable(autoRouterConfig)) + + /** + * Alias for calling [Builder.autoRouterConfig] with `autoRouterConfig.orElse(null)`. + */ + fun autoRouterConfig(autoRouterConfig: Optional) = + autoRouterConfig(autoRouterConfig.getOrNull()) + + /** + * Sets [Builder.autoRouterConfig] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRouterConfig] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun autoRouterConfig(autoRouterConfig: JsonField) = apply { + this.autoRouterConfig = autoRouterConfig + } + + fun autoRouterConfigPath(autoRouterConfigPath: String?) = + autoRouterConfigPath(JsonField.ofNullable(autoRouterConfigPath)) + + /** + * Alias for calling [Builder.autoRouterConfigPath] with + * `autoRouterConfigPath.orElse(null)`. + */ + fun autoRouterConfigPath(autoRouterConfigPath: Optional) = + autoRouterConfigPath(autoRouterConfigPath.getOrNull()) + + /** + * Sets [Builder.autoRouterConfigPath] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRouterConfigPath] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun autoRouterConfigPath(autoRouterConfigPath: JsonField) = apply { + this.autoRouterConfigPath = autoRouterConfigPath + } + + fun autoRouterDefaultModel(autoRouterDefaultModel: String?) = + autoRouterDefaultModel(JsonField.ofNullable(autoRouterDefaultModel)) + + /** + * Alias for calling [Builder.autoRouterDefaultModel] with + * `autoRouterDefaultModel.orElse(null)`. + */ + fun autoRouterDefaultModel(autoRouterDefaultModel: Optional) = + autoRouterDefaultModel(autoRouterDefaultModel.getOrNull()) + + /** + * Sets [Builder.autoRouterDefaultModel] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRouterDefaultModel] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun autoRouterDefaultModel(autoRouterDefaultModel: JsonField) = apply { + this.autoRouterDefaultModel = autoRouterDefaultModel + } + + fun autoRouterEmbeddingModel(autoRouterEmbeddingModel: String?) = + autoRouterEmbeddingModel(JsonField.ofNullable(autoRouterEmbeddingModel)) + + /** + * Alias for calling [Builder.autoRouterEmbeddingModel] with + * `autoRouterEmbeddingModel.orElse(null)`. + */ + fun autoRouterEmbeddingModel(autoRouterEmbeddingModel: Optional) = + autoRouterEmbeddingModel(autoRouterEmbeddingModel.getOrNull()) + + /** + * Sets [Builder.autoRouterEmbeddingModel] to an arbitrary JSON value. + * + * You should usually call [Builder.autoRouterEmbeddingModel] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun autoRouterEmbeddingModel(autoRouterEmbeddingModel: JsonField) = apply { + this.autoRouterEmbeddingModel = autoRouterEmbeddingModel + } + + fun awsAccessKeyId(awsAccessKeyId: String?) = + awsAccessKeyId(JsonField.ofNullable(awsAccessKeyId)) + + /** Alias for calling [Builder.awsAccessKeyId] with `awsAccessKeyId.orElse(null)`. */ + fun awsAccessKeyId(awsAccessKeyId: Optional) = + awsAccessKeyId(awsAccessKeyId.getOrNull()) + + /** + * Sets [Builder.awsAccessKeyId] to an arbitrary JSON value. + * + * You should usually call [Builder.awsAccessKeyId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun awsAccessKeyId(awsAccessKeyId: JsonField) = apply { + this.awsAccessKeyId = awsAccessKeyId + } + + fun awsBedrockRuntimeEndpoint(awsBedrockRuntimeEndpoint: String?) = + awsBedrockRuntimeEndpoint(JsonField.ofNullable(awsBedrockRuntimeEndpoint)) + + /** + * Alias for calling [Builder.awsBedrockRuntimeEndpoint] with + * `awsBedrockRuntimeEndpoint.orElse(null)`. + */ + fun awsBedrockRuntimeEndpoint(awsBedrockRuntimeEndpoint: Optional) = + awsBedrockRuntimeEndpoint(awsBedrockRuntimeEndpoint.getOrNull()) + + /** + * Sets [Builder.awsBedrockRuntimeEndpoint] to an arbitrary JSON value. + * + * You should usually call [Builder.awsBedrockRuntimeEndpoint] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun awsBedrockRuntimeEndpoint(awsBedrockRuntimeEndpoint: JsonField) = apply { + this.awsBedrockRuntimeEndpoint = awsBedrockRuntimeEndpoint + } + + fun awsRegionName(awsRegionName: String?) = + awsRegionName(JsonField.ofNullable(awsRegionName)) + + /** Alias for calling [Builder.awsRegionName] with `awsRegionName.orElse(null)`. */ + fun awsRegionName(awsRegionName: Optional) = + awsRegionName(awsRegionName.getOrNull()) + + /** + * Sets [Builder.awsRegionName] to an arbitrary JSON value. + * + * You should usually call [Builder.awsRegionName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun awsRegionName(awsRegionName: JsonField) = apply { + this.awsRegionName = awsRegionName + } + + fun awsSecretAccessKey(awsSecretAccessKey: String?) = + awsSecretAccessKey(JsonField.ofNullable(awsSecretAccessKey)) + + /** + * Alias for calling [Builder.awsSecretAccessKey] with + * `awsSecretAccessKey.orElse(null)`. + */ + fun awsSecretAccessKey(awsSecretAccessKey: Optional) = + awsSecretAccessKey(awsSecretAccessKey.getOrNull()) + + /** + * Sets [Builder.awsSecretAccessKey] to an arbitrary JSON value. + * + * You should usually call [Builder.awsSecretAccessKey] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun awsSecretAccessKey(awsSecretAccessKey: JsonField) = apply { + this.awsSecretAccessKey = awsSecretAccessKey + } + + fun budgetDuration(budgetDuration: String?) = + budgetDuration(JsonField.ofNullable(budgetDuration)) + + /** Alias for calling [Builder.budgetDuration] with `budgetDuration.orElse(null)`. */ + fun budgetDuration(budgetDuration: Optional) = + budgetDuration(budgetDuration.getOrNull()) + + /** + * Sets [Builder.budgetDuration] to an arbitrary JSON value. + * + * You should usually call [Builder.budgetDuration] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun budgetDuration(budgetDuration: JsonField) = apply { + this.budgetDuration = budgetDuration + } + + fun cacheCreationInputAudioTokenCost(cacheCreationInputAudioTokenCost: Double?) = + cacheCreationInputAudioTokenCost( + JsonField.ofNullable(cacheCreationInputAudioTokenCost) + ) + + /** + * Alias for [Builder.cacheCreationInputAudioTokenCost]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cacheCreationInputAudioTokenCost(cacheCreationInputAudioTokenCost: Double) = + cacheCreationInputAudioTokenCost(cacheCreationInputAudioTokenCost as Double?) + + /** + * Alias for calling [Builder.cacheCreationInputAudioTokenCost] with + * `cacheCreationInputAudioTokenCost.orElse(null)`. + */ + fun cacheCreationInputAudioTokenCost( + cacheCreationInputAudioTokenCost: Optional + ) = cacheCreationInputAudioTokenCost(cacheCreationInputAudioTokenCost.getOrNull()) + + /** + * Sets [Builder.cacheCreationInputAudioTokenCost] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheCreationInputAudioTokenCost] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun cacheCreationInputAudioTokenCost( + cacheCreationInputAudioTokenCost: JsonField + ) = apply { this.cacheCreationInputAudioTokenCost = cacheCreationInputAudioTokenCost } + + fun cacheCreationInputTokenCost(cacheCreationInputTokenCost: Double?) = + cacheCreationInputTokenCost(JsonField.ofNullable(cacheCreationInputTokenCost)) + + /** + * Alias for [Builder.cacheCreationInputTokenCost]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cacheCreationInputTokenCost(cacheCreationInputTokenCost: Double) = + cacheCreationInputTokenCost(cacheCreationInputTokenCost as Double?) + + /** + * Alias for calling [Builder.cacheCreationInputTokenCost] with + * `cacheCreationInputTokenCost.orElse(null)`. + */ + fun cacheCreationInputTokenCost(cacheCreationInputTokenCost: Optional) = + cacheCreationInputTokenCost(cacheCreationInputTokenCost.getOrNull()) + + /** + * Sets [Builder.cacheCreationInputTokenCost] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheCreationInputTokenCost] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun cacheCreationInputTokenCost(cacheCreationInputTokenCost: JsonField) = + apply { + this.cacheCreationInputTokenCost = cacheCreationInputTokenCost + } + + fun cacheCreationInputTokenCostAbove1hr(cacheCreationInputTokenCostAbove1hr: Double?) = + cacheCreationInputTokenCostAbove1hr( + JsonField.ofNullable(cacheCreationInputTokenCostAbove1hr) + ) + + /** + * Alias for [Builder.cacheCreationInputTokenCostAbove1hr]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cacheCreationInputTokenCostAbove1hr(cacheCreationInputTokenCostAbove1hr: Double) = + cacheCreationInputTokenCostAbove1hr(cacheCreationInputTokenCostAbove1hr as Double?) + + /** + * Alias for calling [Builder.cacheCreationInputTokenCostAbove1hr] with + * `cacheCreationInputTokenCostAbove1hr.orElse(null)`. + */ + fun cacheCreationInputTokenCostAbove1hr( + cacheCreationInputTokenCostAbove1hr: Optional + ) = cacheCreationInputTokenCostAbove1hr(cacheCreationInputTokenCostAbove1hr.getOrNull()) + + /** + * Sets [Builder.cacheCreationInputTokenCostAbove1hr] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheCreationInputTokenCostAbove1hr] with a + * well-typed [Double] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun cacheCreationInputTokenCostAbove1hr( + cacheCreationInputTokenCostAbove1hr: JsonField + ) = apply { + this.cacheCreationInputTokenCostAbove1hr = cacheCreationInputTokenCostAbove1hr + } + + fun cacheCreationInputTokenCostAbove200kTokens( + cacheCreationInputTokenCostAbove200kTokens: Double? + ) = + cacheCreationInputTokenCostAbove200kTokens( + JsonField.ofNullable(cacheCreationInputTokenCostAbove200kTokens) + ) + + /** + * Alias for [Builder.cacheCreationInputTokenCostAbove200kTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cacheCreationInputTokenCostAbove200kTokens( + cacheCreationInputTokenCostAbove200kTokens: Double + ) = + cacheCreationInputTokenCostAbove200kTokens( + cacheCreationInputTokenCostAbove200kTokens as Double? + ) + + /** + * Alias for calling [Builder.cacheCreationInputTokenCostAbove200kTokens] with + * `cacheCreationInputTokenCostAbove200kTokens.orElse(null)`. + */ + fun cacheCreationInputTokenCostAbove200kTokens( + cacheCreationInputTokenCostAbove200kTokens: Optional + ) = + cacheCreationInputTokenCostAbove200kTokens( + cacheCreationInputTokenCostAbove200kTokens.getOrNull() + ) + + /** + * Sets [Builder.cacheCreationInputTokenCostAbove200kTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheCreationInputTokenCostAbove200kTokens] with a + * well-typed [Double] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun cacheCreationInputTokenCostAbove200kTokens( + cacheCreationInputTokenCostAbove200kTokens: JsonField + ) = apply { + this.cacheCreationInputTokenCostAbove200kTokens = + cacheCreationInputTokenCostAbove200kTokens + } + + fun cacheReadInputAudioTokenCost(cacheReadInputAudioTokenCost: Double?) = + cacheReadInputAudioTokenCost(JsonField.ofNullable(cacheReadInputAudioTokenCost)) + + /** + * Alias for [Builder.cacheReadInputAudioTokenCost]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cacheReadInputAudioTokenCost(cacheReadInputAudioTokenCost: Double) = + cacheReadInputAudioTokenCost(cacheReadInputAudioTokenCost as Double?) + + /** + * Alias for calling [Builder.cacheReadInputAudioTokenCost] with + * `cacheReadInputAudioTokenCost.orElse(null)`. + */ + fun cacheReadInputAudioTokenCost(cacheReadInputAudioTokenCost: Optional) = + cacheReadInputAudioTokenCost(cacheReadInputAudioTokenCost.getOrNull()) + + /** + * Sets [Builder.cacheReadInputAudioTokenCost] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheReadInputAudioTokenCost] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun cacheReadInputAudioTokenCost(cacheReadInputAudioTokenCost: JsonField) = + apply { + this.cacheReadInputAudioTokenCost = cacheReadInputAudioTokenCost + } + + fun cacheReadInputTokenCost(cacheReadInputTokenCost: Double?) = + cacheReadInputTokenCost(JsonField.ofNullable(cacheReadInputTokenCost)) + + /** + * Alias for [Builder.cacheReadInputTokenCost]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cacheReadInputTokenCost(cacheReadInputTokenCost: Double) = + cacheReadInputTokenCost(cacheReadInputTokenCost as Double?) + + /** + * Alias for calling [Builder.cacheReadInputTokenCost] with + * `cacheReadInputTokenCost.orElse(null)`. + */ + fun cacheReadInputTokenCost(cacheReadInputTokenCost: Optional) = + cacheReadInputTokenCost(cacheReadInputTokenCost.getOrNull()) + + /** + * Sets [Builder.cacheReadInputTokenCost] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheReadInputTokenCost] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun cacheReadInputTokenCost(cacheReadInputTokenCost: JsonField) = apply { + this.cacheReadInputTokenCost = cacheReadInputTokenCost + } + + fun cacheReadInputTokenCostAbove200kTokens( + cacheReadInputTokenCostAbove200kTokens: Double? + ) = + cacheReadInputTokenCostAbove200kTokens( + JsonField.ofNullable(cacheReadInputTokenCostAbove200kTokens) + ) + + /** + * Alias for [Builder.cacheReadInputTokenCostAbove200kTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cacheReadInputTokenCostAbove200kTokens( + cacheReadInputTokenCostAbove200kTokens: Double + ) = + cacheReadInputTokenCostAbove200kTokens( + cacheReadInputTokenCostAbove200kTokens as Double? + ) + + /** + * Alias for calling [Builder.cacheReadInputTokenCostAbove200kTokens] with + * `cacheReadInputTokenCostAbove200kTokens.orElse(null)`. + */ + fun cacheReadInputTokenCostAbove200kTokens( + cacheReadInputTokenCostAbove200kTokens: Optional + ) = + cacheReadInputTokenCostAbove200kTokens( + cacheReadInputTokenCostAbove200kTokens.getOrNull() + ) + + /** + * Sets [Builder.cacheReadInputTokenCostAbove200kTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheReadInputTokenCostAbove200kTokens] with a + * well-typed [Double] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun cacheReadInputTokenCostAbove200kTokens( + cacheReadInputTokenCostAbove200kTokens: JsonField + ) = apply { + this.cacheReadInputTokenCostAbove200kTokens = cacheReadInputTokenCostAbove200kTokens + } + + fun cacheReadInputTokenCostFlex(cacheReadInputTokenCostFlex: Double?) = + cacheReadInputTokenCostFlex(JsonField.ofNullable(cacheReadInputTokenCostFlex)) + + /** + * Alias for [Builder.cacheReadInputTokenCostFlex]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cacheReadInputTokenCostFlex(cacheReadInputTokenCostFlex: Double) = + cacheReadInputTokenCostFlex(cacheReadInputTokenCostFlex as Double?) + + /** + * Alias for calling [Builder.cacheReadInputTokenCostFlex] with + * `cacheReadInputTokenCostFlex.orElse(null)`. + */ + fun cacheReadInputTokenCostFlex(cacheReadInputTokenCostFlex: Optional) = + cacheReadInputTokenCostFlex(cacheReadInputTokenCostFlex.getOrNull()) + + /** + * Sets [Builder.cacheReadInputTokenCostFlex] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheReadInputTokenCostFlex] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun cacheReadInputTokenCostFlex(cacheReadInputTokenCostFlex: JsonField) = + apply { + this.cacheReadInputTokenCostFlex = cacheReadInputTokenCostFlex + } + + fun cacheReadInputTokenCostPriority(cacheReadInputTokenCostPriority: Double?) = + cacheReadInputTokenCostPriority( + JsonField.ofNullable(cacheReadInputTokenCostPriority) + ) + + /** + * Alias for [Builder.cacheReadInputTokenCostPriority]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun cacheReadInputTokenCostPriority(cacheReadInputTokenCostPriority: Double) = + cacheReadInputTokenCostPriority(cacheReadInputTokenCostPriority as Double?) + + /** + * Alias for calling [Builder.cacheReadInputTokenCostPriority] with + * `cacheReadInputTokenCostPriority.orElse(null)`. + */ + fun cacheReadInputTokenCostPriority(cacheReadInputTokenCostPriority: Optional) = + cacheReadInputTokenCostPriority(cacheReadInputTokenCostPriority.getOrNull()) + + /** + * Sets [Builder.cacheReadInputTokenCostPriority] to an arbitrary JSON value. + * + * You should usually call [Builder.cacheReadInputTokenCostPriority] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun cacheReadInputTokenCostPriority( + cacheReadInputTokenCostPriority: JsonField + ) = apply { this.cacheReadInputTokenCostPriority = cacheReadInputTokenCostPriority } + + fun citationCostPerToken(citationCostPerToken: Double?) = + citationCostPerToken(JsonField.ofNullable(citationCostPerToken)) + + /** + * Alias for [Builder.citationCostPerToken]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun citationCostPerToken(citationCostPerToken: Double) = + citationCostPerToken(citationCostPerToken as Double?) + + /** + * Alias for calling [Builder.citationCostPerToken] with + * `citationCostPerToken.orElse(null)`. + */ + fun citationCostPerToken(citationCostPerToken: Optional) = + citationCostPerToken(citationCostPerToken.getOrNull()) + + /** + * Sets [Builder.citationCostPerToken] to an arbitrary JSON value. + * + * You should usually call [Builder.citationCostPerToken] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun citationCostPerToken(citationCostPerToken: JsonField) = apply { + this.citationCostPerToken = citationCostPerToken + } + + fun configurableClientsideAuthParams( + configurableClientsideAuthParams: List? + ) = + configurableClientsideAuthParams( + JsonField.ofNullable(configurableClientsideAuthParams) + ) + + /** + * Alias for calling [Builder.configurableClientsideAuthParams] with + * `configurableClientsideAuthParams.orElse(null)`. + */ + fun configurableClientsideAuthParams( + configurableClientsideAuthParams: Optional> + ) = configurableClientsideAuthParams(configurableClientsideAuthParams.getOrNull()) + + /** + * Sets [Builder.configurableClientsideAuthParams] to an arbitrary JSON value. + * + * You should usually call [Builder.configurableClientsideAuthParams] with a well-typed + * `List` value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ + fun configurableClientsideAuthParams( + configurableClientsideAuthParams: JsonField> + ) = apply { + this.configurableClientsideAuthParams = + configurableClientsideAuthParams.map { it.toMutableList() } + } + + /** + * Adds a single [ConfigurableClientsideAuthParam] to + * [configurableClientsideAuthParams]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addConfigurableClientsideAuthParam( + configurableClientsideAuthParam: ConfigurableClientsideAuthParam + ) = apply { + configurableClientsideAuthParams = + (configurableClientsideAuthParams ?: JsonField.of(mutableListOf())).also { + checkKnown("configurableClientsideAuthParams", it) + .add(configurableClientsideAuthParam) + } + } + + /** + * Alias for calling [addConfigurableClientsideAuthParam] with + * `ConfigurableClientsideAuthParam.ofString(string)`. + */ + fun addConfigurableClientsideAuthParam(string: String) = + addConfigurableClientsideAuthParam(ConfigurableClientsideAuthParam.ofString(string)) + + /** + * Alias for calling [addConfigurableClientsideAuthParam] with + * `ConfigurableClientsideAuthParam.ofParamsCustomAuthInput(paramsCustomAuthInput)`. + */ + fun addConfigurableClientsideAuthParam( + paramsCustomAuthInput: + ConfigurableClientsideAuthParam.ConfigurableClientsideParamsCustomAuthInput + ) = + addConfigurableClientsideAuthParam( + ConfigurableClientsideAuthParam.ofParamsCustomAuthInput(paramsCustomAuthInput) + ) + + fun customLlmProvider(customLlmProvider: String?) = + customLlmProvider(JsonField.ofNullable(customLlmProvider)) + + /** + * Alias for calling [Builder.customLlmProvider] with `customLlmProvider.orElse(null)`. + */ + fun customLlmProvider(customLlmProvider: Optional) = + customLlmProvider(customLlmProvider.getOrNull()) + + /** + * Sets [Builder.customLlmProvider] to an arbitrary JSON value. + * + * You should usually call [Builder.customLlmProvider] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun customLlmProvider(customLlmProvider: JsonField) = apply { + this.customLlmProvider = customLlmProvider + } + + fun gcsBucketName(gcsBucketName: String?) = + gcsBucketName(JsonField.ofNullable(gcsBucketName)) + + /** Alias for calling [Builder.gcsBucketName] with `gcsBucketName.orElse(null)`. */ + fun gcsBucketName(gcsBucketName: Optional) = + gcsBucketName(gcsBucketName.getOrNull()) + + /** + * Sets [Builder.gcsBucketName] to an arbitrary JSON value. + * + * You should usually call [Builder.gcsBucketName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun gcsBucketName(gcsBucketName: JsonField) = apply { + this.gcsBucketName = gcsBucketName + } + + fun inputCostPerAudioPerSecond(inputCostPerAudioPerSecond: Double?) = + inputCostPerAudioPerSecond(JsonField.ofNullable(inputCostPerAudioPerSecond)) + + /** + * Alias for [Builder.inputCostPerAudioPerSecond]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerAudioPerSecond(inputCostPerAudioPerSecond: Double) = + inputCostPerAudioPerSecond(inputCostPerAudioPerSecond as Double?) + + /** + * Alias for calling [Builder.inputCostPerAudioPerSecond] with + * `inputCostPerAudioPerSecond.orElse(null)`. + */ + fun inputCostPerAudioPerSecond(inputCostPerAudioPerSecond: Optional) = + inputCostPerAudioPerSecond(inputCostPerAudioPerSecond.getOrNull()) + + /** + * Sets [Builder.inputCostPerAudioPerSecond] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerAudioPerSecond] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun inputCostPerAudioPerSecond(inputCostPerAudioPerSecond: JsonField) = apply { + this.inputCostPerAudioPerSecond = inputCostPerAudioPerSecond + } + + fun inputCostPerAudioPerSecondAbove128kTokens( + inputCostPerAudioPerSecondAbove128kTokens: Double? + ) = + inputCostPerAudioPerSecondAbove128kTokens( + JsonField.ofNullable(inputCostPerAudioPerSecondAbove128kTokens) + ) + + /** + * Alias for [Builder.inputCostPerAudioPerSecondAbove128kTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerAudioPerSecondAbove128kTokens( + inputCostPerAudioPerSecondAbove128kTokens: Double + ) = + inputCostPerAudioPerSecondAbove128kTokens( + inputCostPerAudioPerSecondAbove128kTokens as Double? + ) + + /** + * Alias for calling [Builder.inputCostPerAudioPerSecondAbove128kTokens] with + * `inputCostPerAudioPerSecondAbove128kTokens.orElse(null)`. + */ + fun inputCostPerAudioPerSecondAbove128kTokens( + inputCostPerAudioPerSecondAbove128kTokens: Optional + ) = + inputCostPerAudioPerSecondAbove128kTokens( + inputCostPerAudioPerSecondAbove128kTokens.getOrNull() + ) + + /** + * Sets [Builder.inputCostPerAudioPerSecondAbove128kTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerAudioPerSecondAbove128kTokens] with a + * well-typed [Double] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun inputCostPerAudioPerSecondAbove128kTokens( + inputCostPerAudioPerSecondAbove128kTokens: JsonField + ) = apply { + this.inputCostPerAudioPerSecondAbove128kTokens = + inputCostPerAudioPerSecondAbove128kTokens + } + + fun inputCostPerAudioToken(inputCostPerAudioToken: Double?) = + inputCostPerAudioToken(JsonField.ofNullable(inputCostPerAudioToken)) + + /** + * Alias for [Builder.inputCostPerAudioToken]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerAudioToken(inputCostPerAudioToken: Double) = + inputCostPerAudioToken(inputCostPerAudioToken as Double?) + + /** + * Alias for calling [Builder.inputCostPerAudioToken] with + * `inputCostPerAudioToken.orElse(null)`. + */ + fun inputCostPerAudioToken(inputCostPerAudioToken: Optional) = + inputCostPerAudioToken(inputCostPerAudioToken.getOrNull()) + + /** + * Sets [Builder.inputCostPerAudioToken] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerAudioToken] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun inputCostPerAudioToken(inputCostPerAudioToken: JsonField) = apply { + this.inputCostPerAudioToken = inputCostPerAudioToken + } + + fun inputCostPerCharacter(inputCostPerCharacter: Double?) = + inputCostPerCharacter(JsonField.ofNullable(inputCostPerCharacter)) + + /** + * Alias for [Builder.inputCostPerCharacter]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerCharacter(inputCostPerCharacter: Double) = + inputCostPerCharacter(inputCostPerCharacter as Double?) + + /** + * Alias for calling [Builder.inputCostPerCharacter] with + * `inputCostPerCharacter.orElse(null)`. + */ + fun inputCostPerCharacter(inputCostPerCharacter: Optional) = + inputCostPerCharacter(inputCostPerCharacter.getOrNull()) + + /** + * Sets [Builder.inputCostPerCharacter] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerCharacter] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun inputCostPerCharacter(inputCostPerCharacter: JsonField) = apply { + this.inputCostPerCharacter = inputCostPerCharacter + } + + fun inputCostPerCharacterAbove128kTokens( + inputCostPerCharacterAbove128kTokens: Double? + ) = + inputCostPerCharacterAbove128kTokens( + JsonField.ofNullable(inputCostPerCharacterAbove128kTokens) + ) + + /** + * Alias for [Builder.inputCostPerCharacterAbove128kTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerCharacterAbove128kTokens(inputCostPerCharacterAbove128kTokens: Double) = + inputCostPerCharacterAbove128kTokens( + inputCostPerCharacterAbove128kTokens as Double? + ) + + /** + * Alias for calling [Builder.inputCostPerCharacterAbove128kTokens] with + * `inputCostPerCharacterAbove128kTokens.orElse(null)`. + */ + fun inputCostPerCharacterAbove128kTokens( + inputCostPerCharacterAbove128kTokens: Optional + ) = + inputCostPerCharacterAbove128kTokens( + inputCostPerCharacterAbove128kTokens.getOrNull() + ) + + /** + * Sets [Builder.inputCostPerCharacterAbove128kTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerCharacterAbove128kTokens] with a + * well-typed [Double] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun inputCostPerCharacterAbove128kTokens( + inputCostPerCharacterAbove128kTokens: JsonField + ) = apply { + this.inputCostPerCharacterAbove128kTokens = inputCostPerCharacterAbove128kTokens + } + + fun inputCostPerImage(inputCostPerImage: Double?) = + inputCostPerImage(JsonField.ofNullable(inputCostPerImage)) + + /** + * Alias for [Builder.inputCostPerImage]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerImage(inputCostPerImage: Double) = + inputCostPerImage(inputCostPerImage as Double?) + + /** + * Alias for calling [Builder.inputCostPerImage] with `inputCostPerImage.orElse(null)`. + */ + fun inputCostPerImage(inputCostPerImage: Optional) = + inputCostPerImage(inputCostPerImage.getOrNull()) + + /** + * Sets [Builder.inputCostPerImage] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerImage] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun inputCostPerImage(inputCostPerImage: JsonField) = apply { + this.inputCostPerImage = inputCostPerImage + } + + fun inputCostPerImageAbove128kTokens(inputCostPerImageAbove128kTokens: Double?) = + inputCostPerImageAbove128kTokens( + JsonField.ofNullable(inputCostPerImageAbove128kTokens) + ) + + /** + * Alias for [Builder.inputCostPerImageAbove128kTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerImageAbove128kTokens(inputCostPerImageAbove128kTokens: Double) = + inputCostPerImageAbove128kTokens(inputCostPerImageAbove128kTokens as Double?) + + /** + * Alias for calling [Builder.inputCostPerImageAbove128kTokens] with + * `inputCostPerImageAbove128kTokens.orElse(null)`. + */ + fun inputCostPerImageAbove128kTokens( + inputCostPerImageAbove128kTokens: Optional + ) = inputCostPerImageAbove128kTokens(inputCostPerImageAbove128kTokens.getOrNull()) + + /** + * Sets [Builder.inputCostPerImageAbove128kTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerImageAbove128kTokens] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun inputCostPerImageAbove128kTokens( + inputCostPerImageAbove128kTokens: JsonField + ) = apply { this.inputCostPerImageAbove128kTokens = inputCostPerImageAbove128kTokens } + + fun inputCostPerPixel(inputCostPerPixel: Double?) = + inputCostPerPixel(JsonField.ofNullable(inputCostPerPixel)) + + /** + * Alias for [Builder.inputCostPerPixel]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerPixel(inputCostPerPixel: Double) = + inputCostPerPixel(inputCostPerPixel as Double?) + + /** + * Alias for calling [Builder.inputCostPerPixel] with `inputCostPerPixel.orElse(null)`. + */ + fun inputCostPerPixel(inputCostPerPixel: Optional) = + inputCostPerPixel(inputCostPerPixel.getOrNull()) + + /** + * Sets [Builder.inputCostPerPixel] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerPixel] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun inputCostPerPixel(inputCostPerPixel: JsonField) = apply { + this.inputCostPerPixel = inputCostPerPixel + } + + fun inputCostPerQuery(inputCostPerQuery: Double?) = + inputCostPerQuery(JsonField.ofNullable(inputCostPerQuery)) + + /** + * Alias for [Builder.inputCostPerQuery]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerQuery(inputCostPerQuery: Double) = + inputCostPerQuery(inputCostPerQuery as Double?) + + /** + * Alias for calling [Builder.inputCostPerQuery] with `inputCostPerQuery.orElse(null)`. + */ + fun inputCostPerQuery(inputCostPerQuery: Optional) = + inputCostPerQuery(inputCostPerQuery.getOrNull()) + + /** + * Sets [Builder.inputCostPerQuery] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerQuery] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun inputCostPerQuery(inputCostPerQuery: JsonField) = apply { + this.inputCostPerQuery = inputCostPerQuery + } + + fun inputCostPerSecond(inputCostPerSecond: Double?) = + inputCostPerSecond(JsonField.ofNullable(inputCostPerSecond)) + + /** + * Alias for [Builder.inputCostPerSecond]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerSecond(inputCostPerSecond: Double) = + inputCostPerSecond(inputCostPerSecond as Double?) + + /** + * Alias for calling [Builder.inputCostPerSecond] with + * `inputCostPerSecond.orElse(null)`. + */ + fun inputCostPerSecond(inputCostPerSecond: Optional) = + inputCostPerSecond(inputCostPerSecond.getOrNull()) + + /** + * Sets [Builder.inputCostPerSecond] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerSecond] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun inputCostPerSecond(inputCostPerSecond: JsonField) = apply { + this.inputCostPerSecond = inputCostPerSecond + } + + fun inputCostPerToken(inputCostPerToken: Double?) = + inputCostPerToken(JsonField.ofNullable(inputCostPerToken)) + + /** + * Alias for [Builder.inputCostPerToken]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerToken(inputCostPerToken: Double) = + inputCostPerToken(inputCostPerToken as Double?) + + /** + * Alias for calling [Builder.inputCostPerToken] with `inputCostPerToken.orElse(null)`. + */ + fun inputCostPerToken(inputCostPerToken: Optional) = + inputCostPerToken(inputCostPerToken.getOrNull()) + + /** + * Sets [Builder.inputCostPerToken] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerToken] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun inputCostPerToken(inputCostPerToken: JsonField) = apply { + this.inputCostPerToken = inputCostPerToken + } + + fun inputCostPerTokenAbove128kTokens(inputCostPerTokenAbove128kTokens: Double?) = + inputCostPerTokenAbove128kTokens( + JsonField.ofNullable(inputCostPerTokenAbove128kTokens) + ) + + /** + * Alias for [Builder.inputCostPerTokenAbove128kTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerTokenAbove128kTokens(inputCostPerTokenAbove128kTokens: Double) = + inputCostPerTokenAbove128kTokens(inputCostPerTokenAbove128kTokens as Double?) + + /** + * Alias for calling [Builder.inputCostPerTokenAbove128kTokens] with + * `inputCostPerTokenAbove128kTokens.orElse(null)`. + */ + fun inputCostPerTokenAbove128kTokens( + inputCostPerTokenAbove128kTokens: Optional + ) = inputCostPerTokenAbove128kTokens(inputCostPerTokenAbove128kTokens.getOrNull()) + + /** + * Sets [Builder.inputCostPerTokenAbove128kTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerTokenAbove128kTokens] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun inputCostPerTokenAbove128kTokens( + inputCostPerTokenAbove128kTokens: JsonField + ) = apply { this.inputCostPerTokenAbove128kTokens = inputCostPerTokenAbove128kTokens } + + fun inputCostPerTokenAbove200kTokens(inputCostPerTokenAbove200kTokens: Double?) = + inputCostPerTokenAbove200kTokens( + JsonField.ofNullable(inputCostPerTokenAbove200kTokens) + ) + + /** + * Alias for [Builder.inputCostPerTokenAbove200kTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerTokenAbove200kTokens(inputCostPerTokenAbove200kTokens: Double) = + inputCostPerTokenAbove200kTokens(inputCostPerTokenAbove200kTokens as Double?) + + /** + * Alias for calling [Builder.inputCostPerTokenAbove200kTokens] with + * `inputCostPerTokenAbove200kTokens.orElse(null)`. + */ + fun inputCostPerTokenAbove200kTokens( + inputCostPerTokenAbove200kTokens: Optional + ) = inputCostPerTokenAbove200kTokens(inputCostPerTokenAbove200kTokens.getOrNull()) + + /** + * Sets [Builder.inputCostPerTokenAbove200kTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerTokenAbove200kTokens] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun inputCostPerTokenAbove200kTokens( + inputCostPerTokenAbove200kTokens: JsonField + ) = apply { this.inputCostPerTokenAbove200kTokens = inputCostPerTokenAbove200kTokens } + + fun inputCostPerTokenBatches(inputCostPerTokenBatches: Double?) = + inputCostPerTokenBatches(JsonField.ofNullable(inputCostPerTokenBatches)) + + /** + * Alias for [Builder.inputCostPerTokenBatches]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerTokenBatches(inputCostPerTokenBatches: Double) = + inputCostPerTokenBatches(inputCostPerTokenBatches as Double?) + + /** + * Alias for calling [Builder.inputCostPerTokenBatches] with + * `inputCostPerTokenBatches.orElse(null)`. + */ + fun inputCostPerTokenBatches(inputCostPerTokenBatches: Optional) = + inputCostPerTokenBatches(inputCostPerTokenBatches.getOrNull()) + + /** + * Sets [Builder.inputCostPerTokenBatches] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerTokenBatches] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun inputCostPerTokenBatches(inputCostPerTokenBatches: JsonField) = apply { + this.inputCostPerTokenBatches = inputCostPerTokenBatches + } + + fun inputCostPerTokenCacheHit(inputCostPerTokenCacheHit: Double?) = + inputCostPerTokenCacheHit(JsonField.ofNullable(inputCostPerTokenCacheHit)) + + /** + * Alias for [Builder.inputCostPerTokenCacheHit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerTokenCacheHit(inputCostPerTokenCacheHit: Double) = + inputCostPerTokenCacheHit(inputCostPerTokenCacheHit as Double?) + + /** + * Alias for calling [Builder.inputCostPerTokenCacheHit] with + * `inputCostPerTokenCacheHit.orElse(null)`. + */ + fun inputCostPerTokenCacheHit(inputCostPerTokenCacheHit: Optional) = + inputCostPerTokenCacheHit(inputCostPerTokenCacheHit.getOrNull()) + + /** + * Sets [Builder.inputCostPerTokenCacheHit] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerTokenCacheHit] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun inputCostPerTokenCacheHit(inputCostPerTokenCacheHit: JsonField) = apply { + this.inputCostPerTokenCacheHit = inputCostPerTokenCacheHit + } + + fun inputCostPerTokenFlex(inputCostPerTokenFlex: Double?) = + inputCostPerTokenFlex(JsonField.ofNullable(inputCostPerTokenFlex)) + + /** + * Alias for [Builder.inputCostPerTokenFlex]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerTokenFlex(inputCostPerTokenFlex: Double) = + inputCostPerTokenFlex(inputCostPerTokenFlex as Double?) + + /** + * Alias for calling [Builder.inputCostPerTokenFlex] with + * `inputCostPerTokenFlex.orElse(null)`. + */ + fun inputCostPerTokenFlex(inputCostPerTokenFlex: Optional) = + inputCostPerTokenFlex(inputCostPerTokenFlex.getOrNull()) + + /** + * Sets [Builder.inputCostPerTokenFlex] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerTokenFlex] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun inputCostPerTokenFlex(inputCostPerTokenFlex: JsonField) = apply { + this.inputCostPerTokenFlex = inputCostPerTokenFlex + } + + fun inputCostPerTokenPriority(inputCostPerTokenPriority: Double?) = + inputCostPerTokenPriority(JsonField.ofNullable(inputCostPerTokenPriority)) + + /** + * Alias for [Builder.inputCostPerTokenPriority]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerTokenPriority(inputCostPerTokenPriority: Double) = + inputCostPerTokenPriority(inputCostPerTokenPriority as Double?) + + /** + * Alias for calling [Builder.inputCostPerTokenPriority] with + * `inputCostPerTokenPriority.orElse(null)`. + */ + fun inputCostPerTokenPriority(inputCostPerTokenPriority: Optional) = + inputCostPerTokenPriority(inputCostPerTokenPriority.getOrNull()) + + /** + * Sets [Builder.inputCostPerTokenPriority] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerTokenPriority] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun inputCostPerTokenPriority(inputCostPerTokenPriority: JsonField) = apply { + this.inputCostPerTokenPriority = inputCostPerTokenPriority + } + + fun inputCostPerVideoPerSecond(inputCostPerVideoPerSecond: Double?) = + inputCostPerVideoPerSecond(JsonField.ofNullable(inputCostPerVideoPerSecond)) + + /** + * Alias for [Builder.inputCostPerVideoPerSecond]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerVideoPerSecond(inputCostPerVideoPerSecond: Double) = + inputCostPerVideoPerSecond(inputCostPerVideoPerSecond as Double?) + + /** + * Alias for calling [Builder.inputCostPerVideoPerSecond] with + * `inputCostPerVideoPerSecond.orElse(null)`. + */ + fun inputCostPerVideoPerSecond(inputCostPerVideoPerSecond: Optional) = + inputCostPerVideoPerSecond(inputCostPerVideoPerSecond.getOrNull()) + + /** + * Sets [Builder.inputCostPerVideoPerSecond] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerVideoPerSecond] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun inputCostPerVideoPerSecond(inputCostPerVideoPerSecond: JsonField) = apply { + this.inputCostPerVideoPerSecond = inputCostPerVideoPerSecond + } + + fun inputCostPerVideoPerSecondAbove128kTokens( + inputCostPerVideoPerSecondAbove128kTokens: Double? + ) = + inputCostPerVideoPerSecondAbove128kTokens( + JsonField.ofNullable(inputCostPerVideoPerSecondAbove128kTokens) + ) + + /** + * Alias for [Builder.inputCostPerVideoPerSecondAbove128kTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerVideoPerSecondAbove128kTokens( + inputCostPerVideoPerSecondAbove128kTokens: Double + ) = + inputCostPerVideoPerSecondAbove128kTokens( + inputCostPerVideoPerSecondAbove128kTokens as Double? + ) + + /** + * Alias for calling [Builder.inputCostPerVideoPerSecondAbove128kTokens] with + * `inputCostPerVideoPerSecondAbove128kTokens.orElse(null)`. + */ + fun inputCostPerVideoPerSecondAbove128kTokens( + inputCostPerVideoPerSecondAbove128kTokens: Optional + ) = + inputCostPerVideoPerSecondAbove128kTokens( + inputCostPerVideoPerSecondAbove128kTokens.getOrNull() + ) + + /** + * Sets [Builder.inputCostPerVideoPerSecondAbove128kTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerVideoPerSecondAbove128kTokens] with a + * well-typed [Double] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun inputCostPerVideoPerSecondAbove128kTokens( + inputCostPerVideoPerSecondAbove128kTokens: JsonField + ) = apply { + this.inputCostPerVideoPerSecondAbove128kTokens = + inputCostPerVideoPerSecondAbove128kTokens + } + + fun inputCostPerVideoPerSecondAbove15sInterval( + inputCostPerVideoPerSecondAbove15sInterval: Double? + ) = + inputCostPerVideoPerSecondAbove15sInterval( + JsonField.ofNullable(inputCostPerVideoPerSecondAbove15sInterval) + ) + + /** + * Alias for [Builder.inputCostPerVideoPerSecondAbove15sInterval]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerVideoPerSecondAbove15sInterval( + inputCostPerVideoPerSecondAbove15sInterval: Double + ) = + inputCostPerVideoPerSecondAbove15sInterval( + inputCostPerVideoPerSecondAbove15sInterval as Double? + ) + + /** + * Alias for calling [Builder.inputCostPerVideoPerSecondAbove15sInterval] with + * `inputCostPerVideoPerSecondAbove15sInterval.orElse(null)`. + */ + fun inputCostPerVideoPerSecondAbove15sInterval( + inputCostPerVideoPerSecondAbove15sInterval: Optional + ) = + inputCostPerVideoPerSecondAbove15sInterval( + inputCostPerVideoPerSecondAbove15sInterval.getOrNull() + ) + + /** + * Sets [Builder.inputCostPerVideoPerSecondAbove15sInterval] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerVideoPerSecondAbove15sInterval] with a + * well-typed [Double] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun inputCostPerVideoPerSecondAbove15sInterval( + inputCostPerVideoPerSecondAbove15sInterval: JsonField + ) = apply { + this.inputCostPerVideoPerSecondAbove15sInterval = + inputCostPerVideoPerSecondAbove15sInterval + } + + fun inputCostPerVideoPerSecondAbove8sInterval( + inputCostPerVideoPerSecondAbove8sInterval: Double? + ) = + inputCostPerVideoPerSecondAbove8sInterval( + JsonField.ofNullable(inputCostPerVideoPerSecondAbove8sInterval) + ) + + /** + * Alias for [Builder.inputCostPerVideoPerSecondAbove8sInterval]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun inputCostPerVideoPerSecondAbove8sInterval( + inputCostPerVideoPerSecondAbove8sInterval: Double + ) = + inputCostPerVideoPerSecondAbove8sInterval( + inputCostPerVideoPerSecondAbove8sInterval as Double? + ) + + /** + * Alias for calling [Builder.inputCostPerVideoPerSecondAbove8sInterval] with + * `inputCostPerVideoPerSecondAbove8sInterval.orElse(null)`. + */ + fun inputCostPerVideoPerSecondAbove8sInterval( + inputCostPerVideoPerSecondAbove8sInterval: Optional + ) = + inputCostPerVideoPerSecondAbove8sInterval( + inputCostPerVideoPerSecondAbove8sInterval.getOrNull() + ) + + /** + * Sets [Builder.inputCostPerVideoPerSecondAbove8sInterval] to an arbitrary JSON value. + * + * You should usually call [Builder.inputCostPerVideoPerSecondAbove8sInterval] with a + * well-typed [Double] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun inputCostPerVideoPerSecondAbove8sInterval( + inputCostPerVideoPerSecondAbove8sInterval: JsonField + ) = apply { + this.inputCostPerVideoPerSecondAbove8sInterval = + inputCostPerVideoPerSecondAbove8sInterval + } + + fun litellmCredentialName(litellmCredentialName: String?) = + litellmCredentialName(JsonField.ofNullable(litellmCredentialName)) + + /** + * Alias for calling [Builder.litellmCredentialName] with + * `litellmCredentialName.orElse(null)`. + */ + fun litellmCredentialName(litellmCredentialName: Optional) = + litellmCredentialName(litellmCredentialName.getOrNull()) + + /** + * Sets [Builder.litellmCredentialName] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmCredentialName] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun litellmCredentialName(litellmCredentialName: JsonField) = apply { + this.litellmCredentialName = litellmCredentialName + } + + fun litellmTraceId(litellmTraceId: String?) = + litellmTraceId(JsonField.ofNullable(litellmTraceId)) + + /** Alias for calling [Builder.litellmTraceId] with `litellmTraceId.orElse(null)`. */ + fun litellmTraceId(litellmTraceId: Optional) = + litellmTraceId(litellmTraceId.getOrNull()) + + /** + * Sets [Builder.litellmTraceId] to an arbitrary JSON value. + * + * You should usually call [Builder.litellmTraceId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun litellmTraceId(litellmTraceId: JsonField) = apply { + this.litellmTraceId = litellmTraceId + } + + fun maxBudget(maxBudget: Double?) = maxBudget(JsonField.ofNullable(maxBudget)) + + /** + * Alias for [Builder.maxBudget]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxBudget(maxBudget: Double) = maxBudget(maxBudget as Double?) + + /** Alias for calling [Builder.maxBudget] with `maxBudget.orElse(null)`. */ + fun maxBudget(maxBudget: Optional) = maxBudget(maxBudget.getOrNull()) + + /** + * Sets [Builder.maxBudget] to an arbitrary JSON value. + * + * You should usually call [Builder.maxBudget] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxBudget(maxBudget: JsonField) = apply { this.maxBudget = maxBudget } + + fun maxFileSizeMb(maxFileSizeMb: Double?) = + maxFileSizeMb(JsonField.ofNullable(maxFileSizeMb)) + + /** + * Alias for [Builder.maxFileSizeMb]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxFileSizeMb(maxFileSizeMb: Double) = maxFileSizeMb(maxFileSizeMb as Double?) + + /** Alias for calling [Builder.maxFileSizeMb] with `maxFileSizeMb.orElse(null)`. */ + fun maxFileSizeMb(maxFileSizeMb: Optional) = + maxFileSizeMb(maxFileSizeMb.getOrNull()) + + /** + * Sets [Builder.maxFileSizeMb] to an arbitrary JSON value. + * + * You should usually call [Builder.maxFileSizeMb] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxFileSizeMb(maxFileSizeMb: JsonField) = apply { + this.maxFileSizeMb = maxFileSizeMb + } + + fun maxRetries(maxRetries: Long?) = maxRetries(JsonField.ofNullable(maxRetries)) + + /** + * Alias for [Builder.maxRetries]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxRetries(maxRetries: Long) = maxRetries(maxRetries as Long?) + + /** Alias for calling [Builder.maxRetries] with `maxRetries.orElse(null)`. */ + fun maxRetries(maxRetries: Optional) = maxRetries(maxRetries.getOrNull()) + + /** + * Sets [Builder.maxRetries] to an arbitrary JSON value. + * + * You should usually call [Builder.maxRetries] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun maxRetries(maxRetries: JsonField) = apply { this.maxRetries = maxRetries } + + fun mergeReasoningContentInChoices(mergeReasoningContentInChoices: Boolean?) = + mergeReasoningContentInChoices(JsonField.ofNullable(mergeReasoningContentInChoices)) + + /** + * Alias for [Builder.mergeReasoningContentInChoices]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun mergeReasoningContentInChoices(mergeReasoningContentInChoices: Boolean) = + mergeReasoningContentInChoices(mergeReasoningContentInChoices as Boolean?) + + /** + * Alias for calling [Builder.mergeReasoningContentInChoices] with + * `mergeReasoningContentInChoices.orElse(null)`. + */ + fun mergeReasoningContentInChoices(mergeReasoningContentInChoices: Optional) = + mergeReasoningContentInChoices(mergeReasoningContentInChoices.getOrNull()) + + /** + * Sets [Builder.mergeReasoningContentInChoices] to an arbitrary JSON value. + * + * You should usually call [Builder.mergeReasoningContentInChoices] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun mergeReasoningContentInChoices(mergeReasoningContentInChoices: JsonField) = + apply { + this.mergeReasoningContentInChoices = mergeReasoningContentInChoices + } + + fun milvusTextField(milvusTextField: String?) = + milvusTextField(JsonField.ofNullable(milvusTextField)) + + /** Alias for calling [Builder.milvusTextField] with `milvusTextField.orElse(null)`. */ + fun milvusTextField(milvusTextField: Optional) = + milvusTextField(milvusTextField.getOrNull()) + + /** + * Sets [Builder.milvusTextField] to an arbitrary JSON value. + * + * You should usually call [Builder.milvusTextField] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun milvusTextField(milvusTextField: JsonField) = apply { + this.milvusTextField = milvusTextField + } + + fun mockResponse(mockResponse: MockResponse?) = + mockResponse(JsonField.ofNullable(mockResponse)) + + /** Alias for calling [Builder.mockResponse] with `mockResponse.orElse(null)`. */ + fun mockResponse(mockResponse: Optional) = + mockResponse(mockResponse.getOrNull()) + + /** + * Sets [Builder.mockResponse] to an arbitrary JSON value. + * + * You should usually call [Builder.mockResponse] with a well-typed [MockResponse] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun mockResponse(mockResponse: JsonField) = apply { + this.mockResponse = mockResponse + } + + /** Alias for calling [mockResponse] with `MockResponse.ofString(string)`. */ + fun mockResponse(string: String) = mockResponse(MockResponse.ofString(string)) + + /** Alias for calling [mockResponse] with `MockResponse.ofModel(model)`. */ + fun mockResponse(model: MockResponse.ModelResponse) = + mockResponse(MockResponse.ofModel(model)) + + /** Alias for calling [mockResponse] with `MockResponse.ofJsonValue(jsonValue)`. */ + fun mockResponse(jsonValue: JsonValue) = + mockResponse(MockResponse.ofJsonValue(jsonValue)) + + fun modelInfo(modelInfo: ModelInfo?) = modelInfo(JsonField.ofNullable(modelInfo)) + + /** Alias for calling [Builder.modelInfo] with `modelInfo.orElse(null)`. */ + fun modelInfo(modelInfo: Optional) = modelInfo(modelInfo.getOrNull()) + + /** + * Sets [Builder.modelInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.modelInfo] with a well-typed [ModelInfo] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun modelInfo(modelInfo: JsonField) = apply { this.modelInfo = modelInfo } + + fun organization(organization: String?) = + organization(JsonField.ofNullable(organization)) + + /** Alias for calling [Builder.organization] with `organization.orElse(null)`. */ + fun organization(organization: Optional) = + organization(organization.getOrNull()) + + /** + * Sets [Builder.organization] to an arbitrary JSON value. + * + * You should usually call [Builder.organization] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun organization(organization: JsonField) = apply { + this.organization = organization + } + + fun outputCostPerAudioPerSecond(outputCostPerAudioPerSecond: Double?) = + outputCostPerAudioPerSecond(JsonField.ofNullable(outputCostPerAudioPerSecond)) + + /** + * Alias for [Builder.outputCostPerAudioPerSecond]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerAudioPerSecond(outputCostPerAudioPerSecond: Double) = + outputCostPerAudioPerSecond(outputCostPerAudioPerSecond as Double?) + + /** + * Alias for calling [Builder.outputCostPerAudioPerSecond] with + * `outputCostPerAudioPerSecond.orElse(null)`. + */ + fun outputCostPerAudioPerSecond(outputCostPerAudioPerSecond: Optional) = + outputCostPerAudioPerSecond(outputCostPerAudioPerSecond.getOrNull()) + + /** + * Sets [Builder.outputCostPerAudioPerSecond] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerAudioPerSecond] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun outputCostPerAudioPerSecond(outputCostPerAudioPerSecond: JsonField) = + apply { + this.outputCostPerAudioPerSecond = outputCostPerAudioPerSecond + } + + fun outputCostPerAudioToken(outputCostPerAudioToken: Double?) = + outputCostPerAudioToken(JsonField.ofNullable(outputCostPerAudioToken)) + + /** + * Alias for [Builder.outputCostPerAudioToken]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerAudioToken(outputCostPerAudioToken: Double) = + outputCostPerAudioToken(outputCostPerAudioToken as Double?) + + /** + * Alias for calling [Builder.outputCostPerAudioToken] with + * `outputCostPerAudioToken.orElse(null)`. + */ + fun outputCostPerAudioToken(outputCostPerAudioToken: Optional) = + outputCostPerAudioToken(outputCostPerAudioToken.getOrNull()) + + /** + * Sets [Builder.outputCostPerAudioToken] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerAudioToken] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun outputCostPerAudioToken(outputCostPerAudioToken: JsonField) = apply { + this.outputCostPerAudioToken = outputCostPerAudioToken + } + + fun outputCostPerCharacter(outputCostPerCharacter: Double?) = + outputCostPerCharacter(JsonField.ofNullable(outputCostPerCharacter)) + + /** + * Alias for [Builder.outputCostPerCharacter]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerCharacter(outputCostPerCharacter: Double) = + outputCostPerCharacter(outputCostPerCharacter as Double?) + + /** + * Alias for calling [Builder.outputCostPerCharacter] with + * `outputCostPerCharacter.orElse(null)`. + */ + fun outputCostPerCharacter(outputCostPerCharacter: Optional) = + outputCostPerCharacter(outputCostPerCharacter.getOrNull()) + + /** + * Sets [Builder.outputCostPerCharacter] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerCharacter] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun outputCostPerCharacter(outputCostPerCharacter: JsonField) = apply { + this.outputCostPerCharacter = outputCostPerCharacter + } + + fun outputCostPerCharacterAbove128kTokens( + outputCostPerCharacterAbove128kTokens: Double? + ) = + outputCostPerCharacterAbove128kTokens( + JsonField.ofNullable(outputCostPerCharacterAbove128kTokens) + ) + + /** + * Alias for [Builder.outputCostPerCharacterAbove128kTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerCharacterAbove128kTokens( + outputCostPerCharacterAbove128kTokens: Double + ) = + outputCostPerCharacterAbove128kTokens( + outputCostPerCharacterAbove128kTokens as Double? + ) + + /** + * Alias for calling [Builder.outputCostPerCharacterAbove128kTokens] with + * `outputCostPerCharacterAbove128kTokens.orElse(null)`. + */ + fun outputCostPerCharacterAbove128kTokens( + outputCostPerCharacterAbove128kTokens: Optional + ) = + outputCostPerCharacterAbove128kTokens( + outputCostPerCharacterAbove128kTokens.getOrNull() + ) + + /** + * Sets [Builder.outputCostPerCharacterAbove128kTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerCharacterAbove128kTokens] with a + * well-typed [Double] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun outputCostPerCharacterAbove128kTokens( + outputCostPerCharacterAbove128kTokens: JsonField + ) = apply { + this.outputCostPerCharacterAbove128kTokens = outputCostPerCharacterAbove128kTokens + } + + fun outputCostPerImage(outputCostPerImage: Double?) = + outputCostPerImage(JsonField.ofNullable(outputCostPerImage)) + + /** + * Alias for [Builder.outputCostPerImage]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerImage(outputCostPerImage: Double) = + outputCostPerImage(outputCostPerImage as Double?) + + /** + * Alias for calling [Builder.outputCostPerImage] with + * `outputCostPerImage.orElse(null)`. + */ + fun outputCostPerImage(outputCostPerImage: Optional) = + outputCostPerImage(outputCostPerImage.getOrNull()) + + /** + * Sets [Builder.outputCostPerImage] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerImage] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun outputCostPerImage(outputCostPerImage: JsonField) = apply { + this.outputCostPerImage = outputCostPerImage + } + + fun outputCostPerImageToken(outputCostPerImageToken: Double?) = + outputCostPerImageToken(JsonField.ofNullable(outputCostPerImageToken)) + + /** + * Alias for [Builder.outputCostPerImageToken]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerImageToken(outputCostPerImageToken: Double) = + outputCostPerImageToken(outputCostPerImageToken as Double?) + + /** + * Alias for calling [Builder.outputCostPerImageToken] with + * `outputCostPerImageToken.orElse(null)`. + */ + fun outputCostPerImageToken(outputCostPerImageToken: Optional) = + outputCostPerImageToken(outputCostPerImageToken.getOrNull()) + + /** + * Sets [Builder.outputCostPerImageToken] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerImageToken] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun outputCostPerImageToken(outputCostPerImageToken: JsonField) = apply { + this.outputCostPerImageToken = outputCostPerImageToken + } + + fun outputCostPerPixel(outputCostPerPixel: Double?) = + outputCostPerPixel(JsonField.ofNullable(outputCostPerPixel)) + + /** + * Alias for [Builder.outputCostPerPixel]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerPixel(outputCostPerPixel: Double) = + outputCostPerPixel(outputCostPerPixel as Double?) + + /** + * Alias for calling [Builder.outputCostPerPixel] with + * `outputCostPerPixel.orElse(null)`. + */ + fun outputCostPerPixel(outputCostPerPixel: Optional) = + outputCostPerPixel(outputCostPerPixel.getOrNull()) + + /** + * Sets [Builder.outputCostPerPixel] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerPixel] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun outputCostPerPixel(outputCostPerPixel: JsonField) = apply { + this.outputCostPerPixel = outputCostPerPixel + } + + fun outputCostPerReasoningToken(outputCostPerReasoningToken: Double?) = + outputCostPerReasoningToken(JsonField.ofNullable(outputCostPerReasoningToken)) + + /** + * Alias for [Builder.outputCostPerReasoningToken]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerReasoningToken(outputCostPerReasoningToken: Double) = + outputCostPerReasoningToken(outputCostPerReasoningToken as Double?) + + /** + * Alias for calling [Builder.outputCostPerReasoningToken] with + * `outputCostPerReasoningToken.orElse(null)`. + */ + fun outputCostPerReasoningToken(outputCostPerReasoningToken: Optional) = + outputCostPerReasoningToken(outputCostPerReasoningToken.getOrNull()) + + /** + * Sets [Builder.outputCostPerReasoningToken] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerReasoningToken] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun outputCostPerReasoningToken(outputCostPerReasoningToken: JsonField) = + apply { + this.outputCostPerReasoningToken = outputCostPerReasoningToken + } + + fun outputCostPerSecond(outputCostPerSecond: Double?) = + outputCostPerSecond(JsonField.ofNullable(outputCostPerSecond)) + + /** + * Alias for [Builder.outputCostPerSecond]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerSecond(outputCostPerSecond: Double) = + outputCostPerSecond(outputCostPerSecond as Double?) + + /** + * Alias for calling [Builder.outputCostPerSecond] with + * `outputCostPerSecond.orElse(null)`. + */ + fun outputCostPerSecond(outputCostPerSecond: Optional) = + outputCostPerSecond(outputCostPerSecond.getOrNull()) + + /** + * Sets [Builder.outputCostPerSecond] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerSecond] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun outputCostPerSecond(outputCostPerSecond: JsonField) = apply { + this.outputCostPerSecond = outputCostPerSecond + } + + fun outputCostPerToken(outputCostPerToken: Double?) = + outputCostPerToken(JsonField.ofNullable(outputCostPerToken)) + + /** + * Alias for [Builder.outputCostPerToken]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerToken(outputCostPerToken: Double) = + outputCostPerToken(outputCostPerToken as Double?) + + /** + * Alias for calling [Builder.outputCostPerToken] with + * `outputCostPerToken.orElse(null)`. + */ + fun outputCostPerToken(outputCostPerToken: Optional) = + outputCostPerToken(outputCostPerToken.getOrNull()) + + /** + * Sets [Builder.outputCostPerToken] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerToken] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun outputCostPerToken(outputCostPerToken: JsonField) = apply { + this.outputCostPerToken = outputCostPerToken + } + + fun outputCostPerTokenAbove128kTokens(outputCostPerTokenAbove128kTokens: Double?) = + outputCostPerTokenAbove128kTokens( + JsonField.ofNullable(outputCostPerTokenAbove128kTokens) + ) + + /** + * Alias for [Builder.outputCostPerTokenAbove128kTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerTokenAbove128kTokens(outputCostPerTokenAbove128kTokens: Double) = + outputCostPerTokenAbove128kTokens(outputCostPerTokenAbove128kTokens as Double?) + + /** + * Alias for calling [Builder.outputCostPerTokenAbove128kTokens] with + * `outputCostPerTokenAbove128kTokens.orElse(null)`. + */ + fun outputCostPerTokenAbove128kTokens( + outputCostPerTokenAbove128kTokens: Optional + ) = outputCostPerTokenAbove128kTokens(outputCostPerTokenAbove128kTokens.getOrNull()) + + /** + * Sets [Builder.outputCostPerTokenAbove128kTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerTokenAbove128kTokens] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun outputCostPerTokenAbove128kTokens( + outputCostPerTokenAbove128kTokens: JsonField + ) = apply { this.outputCostPerTokenAbove128kTokens = outputCostPerTokenAbove128kTokens } + + fun outputCostPerTokenAbove200kTokens(outputCostPerTokenAbove200kTokens: Double?) = + outputCostPerTokenAbove200kTokens( + JsonField.ofNullable(outputCostPerTokenAbove200kTokens) + ) + + /** + * Alias for [Builder.outputCostPerTokenAbove200kTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerTokenAbove200kTokens(outputCostPerTokenAbove200kTokens: Double) = + outputCostPerTokenAbove200kTokens(outputCostPerTokenAbove200kTokens as Double?) + + /** + * Alias for calling [Builder.outputCostPerTokenAbove200kTokens] with + * `outputCostPerTokenAbove200kTokens.orElse(null)`. + */ + fun outputCostPerTokenAbove200kTokens( + outputCostPerTokenAbove200kTokens: Optional + ) = outputCostPerTokenAbove200kTokens(outputCostPerTokenAbove200kTokens.getOrNull()) + + /** + * Sets [Builder.outputCostPerTokenAbove200kTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerTokenAbove200kTokens] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun outputCostPerTokenAbove200kTokens( + outputCostPerTokenAbove200kTokens: JsonField + ) = apply { this.outputCostPerTokenAbove200kTokens = outputCostPerTokenAbove200kTokens } + + fun outputCostPerTokenBatches(outputCostPerTokenBatches: Double?) = + outputCostPerTokenBatches(JsonField.ofNullable(outputCostPerTokenBatches)) + + /** + * Alias for [Builder.outputCostPerTokenBatches]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerTokenBatches(outputCostPerTokenBatches: Double) = + outputCostPerTokenBatches(outputCostPerTokenBatches as Double?) + + /** + * Alias for calling [Builder.outputCostPerTokenBatches] with + * `outputCostPerTokenBatches.orElse(null)`. + */ + fun outputCostPerTokenBatches(outputCostPerTokenBatches: Optional) = + outputCostPerTokenBatches(outputCostPerTokenBatches.getOrNull()) + + /** + * Sets [Builder.outputCostPerTokenBatches] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerTokenBatches] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun outputCostPerTokenBatches(outputCostPerTokenBatches: JsonField) = apply { + this.outputCostPerTokenBatches = outputCostPerTokenBatches + } + + fun outputCostPerTokenFlex(outputCostPerTokenFlex: Double?) = + outputCostPerTokenFlex(JsonField.ofNullable(outputCostPerTokenFlex)) + + /** + * Alias for [Builder.outputCostPerTokenFlex]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerTokenFlex(outputCostPerTokenFlex: Double) = + outputCostPerTokenFlex(outputCostPerTokenFlex as Double?) + + /** + * Alias for calling [Builder.outputCostPerTokenFlex] with + * `outputCostPerTokenFlex.orElse(null)`. + */ + fun outputCostPerTokenFlex(outputCostPerTokenFlex: Optional) = + outputCostPerTokenFlex(outputCostPerTokenFlex.getOrNull()) + + /** + * Sets [Builder.outputCostPerTokenFlex] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerTokenFlex] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun outputCostPerTokenFlex(outputCostPerTokenFlex: JsonField) = apply { + this.outputCostPerTokenFlex = outputCostPerTokenFlex + } + + fun outputCostPerTokenPriority(outputCostPerTokenPriority: Double?) = + outputCostPerTokenPriority(JsonField.ofNullable(outputCostPerTokenPriority)) + + /** + * Alias for [Builder.outputCostPerTokenPriority]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerTokenPriority(outputCostPerTokenPriority: Double) = + outputCostPerTokenPriority(outputCostPerTokenPriority as Double?) + + /** + * Alias for calling [Builder.outputCostPerTokenPriority] with + * `outputCostPerTokenPriority.orElse(null)`. + */ + fun outputCostPerTokenPriority(outputCostPerTokenPriority: Optional) = + outputCostPerTokenPriority(outputCostPerTokenPriority.getOrNull()) + + /** + * Sets [Builder.outputCostPerTokenPriority] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerTokenPriority] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun outputCostPerTokenPriority(outputCostPerTokenPriority: JsonField) = apply { + this.outputCostPerTokenPriority = outputCostPerTokenPriority + } + + fun outputCostPerVideoPerSecond(outputCostPerVideoPerSecond: Double?) = + outputCostPerVideoPerSecond(JsonField.ofNullable(outputCostPerVideoPerSecond)) + + /** + * Alias for [Builder.outputCostPerVideoPerSecond]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun outputCostPerVideoPerSecond(outputCostPerVideoPerSecond: Double) = + outputCostPerVideoPerSecond(outputCostPerVideoPerSecond as Double?) + + /** + * Alias for calling [Builder.outputCostPerVideoPerSecond] with + * `outputCostPerVideoPerSecond.orElse(null)`. + */ + fun outputCostPerVideoPerSecond(outputCostPerVideoPerSecond: Optional) = + outputCostPerVideoPerSecond(outputCostPerVideoPerSecond.getOrNull()) + + /** + * Sets [Builder.outputCostPerVideoPerSecond] to an arbitrary JSON value. + * + * You should usually call [Builder.outputCostPerVideoPerSecond] with a well-typed + * [Double] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun outputCostPerVideoPerSecond(outputCostPerVideoPerSecond: JsonField) = + apply { + this.outputCostPerVideoPerSecond = outputCostPerVideoPerSecond + } + + fun regionName(regionName: String?) = regionName(JsonField.ofNullable(regionName)) + + /** Alias for calling [Builder.regionName] with `regionName.orElse(null)`. */ + fun regionName(regionName: Optional) = regionName(regionName.getOrNull()) + + /** + * Sets [Builder.regionName] to an arbitrary JSON value. + * + * You should usually call [Builder.regionName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun regionName(regionName: JsonField) = apply { this.regionName = regionName } + + fun rpm(rpm: Long?) = rpm(JsonField.ofNullable(rpm)) + + /** + * Alias for [Builder.rpm]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun rpm(rpm: Long) = rpm(rpm as Long?) + + /** Alias for calling [Builder.rpm] with `rpm.orElse(null)`. */ + fun rpm(rpm: Optional) = rpm(rpm.getOrNull()) + + /** + * Sets [Builder.rpm] to an arbitrary JSON value. + * + * You should usually call [Builder.rpm] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rpm(rpm: JsonField) = apply { this.rpm = rpm } + + fun s3BucketName(s3BucketName: String?) = + s3BucketName(JsonField.ofNullable(s3BucketName)) + + /** Alias for calling [Builder.s3BucketName] with `s3BucketName.orElse(null)`. */ + fun s3BucketName(s3BucketName: Optional) = + s3BucketName(s3BucketName.getOrNull()) + + /** + * Sets [Builder.s3BucketName] to an arbitrary JSON value. + * + * You should usually call [Builder.s3BucketName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun s3BucketName(s3BucketName: JsonField) = apply { + this.s3BucketName = s3BucketName + } + + fun s3EncryptionKeyId(s3EncryptionKeyId: String?) = + s3EncryptionKeyId(JsonField.ofNullable(s3EncryptionKeyId)) + + /** + * Alias for calling [Builder.s3EncryptionKeyId] with `s3EncryptionKeyId.orElse(null)`. + */ + fun s3EncryptionKeyId(s3EncryptionKeyId: Optional) = + s3EncryptionKeyId(s3EncryptionKeyId.getOrNull()) + + /** + * Sets [Builder.s3EncryptionKeyId] to an arbitrary JSON value. + * + * You should usually call [Builder.s3EncryptionKeyId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun s3EncryptionKeyId(s3EncryptionKeyId: JsonField) = apply { + this.s3EncryptionKeyId = s3EncryptionKeyId + } + + fun searchContextCostPerQuery(searchContextCostPerQuery: SearchContextCostPerQuery?) = + searchContextCostPerQuery(JsonField.ofNullable(searchContextCostPerQuery)) + + /** + * Alias for calling [Builder.searchContextCostPerQuery] with + * `searchContextCostPerQuery.orElse(null)`. + */ + fun searchContextCostPerQuery( + searchContextCostPerQuery: Optional + ) = searchContextCostPerQuery(searchContextCostPerQuery.getOrNull()) + + /** + * Sets [Builder.searchContextCostPerQuery] to an arbitrary JSON value. + * + * You should usually call [Builder.searchContextCostPerQuery] with a well-typed + * [SearchContextCostPerQuery] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun searchContextCostPerQuery( + searchContextCostPerQuery: JsonField + ) = apply { this.searchContextCostPerQuery = searchContextCostPerQuery } + + fun streamTimeout(streamTimeout: StreamTimeout?) = + streamTimeout(JsonField.ofNullable(streamTimeout)) + + /** Alias for calling [Builder.streamTimeout] with `streamTimeout.orElse(null)`. */ + fun streamTimeout(streamTimeout: Optional) = + streamTimeout(streamTimeout.getOrNull()) + + /** + * Sets [Builder.streamTimeout] to an arbitrary JSON value. + * + * You should usually call [Builder.streamTimeout] with a well-typed [StreamTimeout] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun streamTimeout(streamTimeout: JsonField) = apply { + this.streamTimeout = streamTimeout + } + + /** Alias for calling [streamTimeout] with `StreamTimeout.ofNumber(number)`. */ + fun streamTimeout(number: Double) = streamTimeout(StreamTimeout.ofNumber(number)) + + /** Alias for calling [streamTimeout] with `StreamTimeout.ofString(string)`. */ + fun streamTimeout(string: String) = streamTimeout(StreamTimeout.ofString(string)) + + fun tieredPricing(tieredPricing: List?) = + tieredPricing(JsonField.ofNullable(tieredPricing)) + + /** Alias for calling [Builder.tieredPricing] with `tieredPricing.orElse(null)`. */ + fun tieredPricing(tieredPricing: Optional>) = + tieredPricing(tieredPricing.getOrNull()) + + /** + * Sets [Builder.tieredPricing] to an arbitrary JSON value. + * + * You should usually call [Builder.tieredPricing] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun tieredPricing(tieredPricing: JsonField>) = apply { + this.tieredPricing = tieredPricing.map { it.toMutableList() } + } + + /** + * Adds a single [TieredPricing] to [Builder.tieredPricing]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTieredPricing(tieredPricing: TieredPricing) = apply { + this.tieredPricing = + (this.tieredPricing ?: JsonField.of(mutableListOf())).also { + checkKnown("tieredPricing", it).add(tieredPricing) + } + } + + fun timeout(timeout: Timeout?) = timeout(JsonField.ofNullable(timeout)) + + /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ + fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Timeout] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + /** Alias for calling [timeout] with `Timeout.ofNumber(number)`. */ + fun timeout(number: Double) = timeout(Timeout.ofNumber(number)) + + /** Alias for calling [timeout] with `Timeout.ofString(string)`. */ + fun timeout(string: String) = timeout(Timeout.ofString(string)) + + fun tpm(tpm: Long?) = tpm(JsonField.ofNullable(tpm)) + + /** + * Alias for [Builder.tpm]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun tpm(tpm: Long) = tpm(tpm as Long?) + + /** Alias for calling [Builder.tpm] with `tpm.orElse(null)`. */ + fun tpm(tpm: Optional) = tpm(tpm.getOrNull()) + + /** + * Sets [Builder.tpm] to an arbitrary JSON value. + * + * You should usually call [Builder.tpm] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tpm(tpm: JsonField) = apply { this.tpm = tpm } + + fun useInPassThrough(useInPassThrough: Boolean?) = + useInPassThrough(JsonField.ofNullable(useInPassThrough)) + + /** + * Alias for [Builder.useInPassThrough]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun useInPassThrough(useInPassThrough: Boolean) = + useInPassThrough(useInPassThrough as Boolean?) + + /** + * Alias for calling [Builder.useInPassThrough] with `useInPassThrough.orElse(null)`. + */ + fun useInPassThrough(useInPassThrough: Optional) = + useInPassThrough(useInPassThrough.getOrNull()) + + /** + * Sets [Builder.useInPassThrough] to an arbitrary JSON value. + * + * You should usually call [Builder.useInPassThrough] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun useInPassThrough(useInPassThrough: JsonField) = apply { + this.useInPassThrough = useInPassThrough + } + + fun useLitellmProxy(useLitellmProxy: Boolean?) = + useLitellmProxy(JsonField.ofNullable(useLitellmProxy)) + + /** + * Alias for [Builder.useLitellmProxy]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun useLitellmProxy(useLitellmProxy: Boolean) = + useLitellmProxy(useLitellmProxy as Boolean?) + + /** Alias for calling [Builder.useLitellmProxy] with `useLitellmProxy.orElse(null)`. */ + fun useLitellmProxy(useLitellmProxy: Optional) = + useLitellmProxy(useLitellmProxy.getOrNull()) + + /** + * Sets [Builder.useLitellmProxy] to an arbitrary JSON value. + * + * You should usually call [Builder.useLitellmProxy] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun useLitellmProxy(useLitellmProxy: JsonField) = apply { + this.useLitellmProxy = useLitellmProxy + } + + fun vectorStoreId(vectorStoreId: String?) = + vectorStoreId(JsonField.ofNullable(vectorStoreId)) + + /** Alias for calling [Builder.vectorStoreId] with `vectorStoreId.orElse(null)`. */ + fun vectorStoreId(vectorStoreId: Optional) = + vectorStoreId(vectorStoreId.getOrNull()) + + /** + * Sets [Builder.vectorStoreId] to an arbitrary JSON value. + * + * You should usually call [Builder.vectorStoreId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun vectorStoreId(vectorStoreId: JsonField) = apply { + this.vectorStoreId = vectorStoreId + } + + fun vertexCredentials(vertexCredentials: VertexCredentials?) = + vertexCredentials(JsonField.ofNullable(vertexCredentials)) + + /** + * Alias for calling [Builder.vertexCredentials] with `vertexCredentials.orElse(null)`. + */ + fun vertexCredentials(vertexCredentials: Optional) = + vertexCredentials(vertexCredentials.getOrNull()) + + /** + * Sets [Builder.vertexCredentials] to an arbitrary JSON value. + * + * You should usually call [Builder.vertexCredentials] with a well-typed + * [VertexCredentials] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun vertexCredentials(vertexCredentials: JsonField) = apply { + this.vertexCredentials = vertexCredentials + } + + /** Alias for calling [vertexCredentials] with `VertexCredentials.ofString(string)`. */ + fun vertexCredentials(string: String) = + vertexCredentials(VertexCredentials.ofString(string)) + + /** + * Alias for calling [vertexCredentials] with + * `VertexCredentials.ofUnionMember1(unionMember1)`. + */ + fun vertexCredentials(unionMember1: VertexCredentials.UnionMember1) = + vertexCredentials(VertexCredentials.ofUnionMember1(unionMember1)) + + fun vertexLocation(vertexLocation: String?) = + vertexLocation(JsonField.ofNullable(vertexLocation)) + + /** Alias for calling [Builder.vertexLocation] with `vertexLocation.orElse(null)`. */ + fun vertexLocation(vertexLocation: Optional) = + vertexLocation(vertexLocation.getOrNull()) + + /** + * Sets [Builder.vertexLocation] to an arbitrary JSON value. + * + * You should usually call [Builder.vertexLocation] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun vertexLocation(vertexLocation: JsonField) = apply { + this.vertexLocation = vertexLocation + } + + fun vertexProject(vertexProject: String?) = + vertexProject(JsonField.ofNullable(vertexProject)) + + /** Alias for calling [Builder.vertexProject] with `vertexProject.orElse(null)`. */ + fun vertexProject(vertexProject: Optional) = + vertexProject(vertexProject.getOrNull()) + + /** + * Sets [Builder.vertexProject] to an arbitrary JSON value. + * + * You should usually call [Builder.vertexProject] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun vertexProject(vertexProject: JsonField) = apply { + this.vertexProject = vertexProject + } + + fun watsonxRegionName(watsonxRegionName: String?) = + watsonxRegionName(JsonField.ofNullable(watsonxRegionName)) + + /** + * Alias for calling [Builder.watsonxRegionName] with `watsonxRegionName.orElse(null)`. + */ + fun watsonxRegionName(watsonxRegionName: Optional) = + watsonxRegionName(watsonxRegionName.getOrNull()) + + /** + * Sets [Builder.watsonxRegionName] to an arbitrary JSON value. + * + * You should usually call [Builder.watsonxRegionName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun watsonxRegionName(watsonxRegionName: JsonField) = apply { + this.watsonxRegionName = watsonxRegionName + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [LitellmParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .model() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): LitellmParams = + LitellmParams( + checkRequired("model", model), + apiBase, + apiKey, + apiVersion, + autoRouterConfig, + autoRouterConfigPath, + autoRouterDefaultModel, + autoRouterEmbeddingModel, + awsAccessKeyId, + awsBedrockRuntimeEndpoint, + awsRegionName, + awsSecretAccessKey, + budgetDuration, + cacheCreationInputAudioTokenCost, + cacheCreationInputTokenCost, + cacheCreationInputTokenCostAbove1hr, + cacheCreationInputTokenCostAbove200kTokens, + cacheReadInputAudioTokenCost, + cacheReadInputTokenCost, + cacheReadInputTokenCostAbove200kTokens, + cacheReadInputTokenCostFlex, + cacheReadInputTokenCostPriority, + citationCostPerToken, + (configurableClientsideAuthParams ?: JsonMissing.of()).map { it.toImmutable() }, + customLlmProvider, + gcsBucketName, + inputCostPerAudioPerSecond, + inputCostPerAudioPerSecondAbove128kTokens, + inputCostPerAudioToken, + inputCostPerCharacter, + inputCostPerCharacterAbove128kTokens, + inputCostPerImage, + inputCostPerImageAbove128kTokens, + inputCostPerPixel, + inputCostPerQuery, + inputCostPerSecond, + inputCostPerToken, + inputCostPerTokenAbove128kTokens, + inputCostPerTokenAbove200kTokens, + inputCostPerTokenBatches, + inputCostPerTokenCacheHit, + inputCostPerTokenFlex, + inputCostPerTokenPriority, + inputCostPerVideoPerSecond, + inputCostPerVideoPerSecondAbove128kTokens, + inputCostPerVideoPerSecondAbove15sInterval, + inputCostPerVideoPerSecondAbove8sInterval, + litellmCredentialName, + litellmTraceId, + maxBudget, + maxFileSizeMb, + maxRetries, + mergeReasoningContentInChoices, + milvusTextField, + mockResponse, + modelInfo, + organization, + outputCostPerAudioPerSecond, + outputCostPerAudioToken, + outputCostPerCharacter, + outputCostPerCharacterAbove128kTokens, + outputCostPerImage, + outputCostPerImageToken, + outputCostPerPixel, + outputCostPerReasoningToken, + outputCostPerSecond, + outputCostPerToken, + outputCostPerTokenAbove128kTokens, + outputCostPerTokenAbove200kTokens, + outputCostPerTokenBatches, + outputCostPerTokenFlex, + outputCostPerTokenPriority, + outputCostPerVideoPerSecond, + regionName, + rpm, + s3BucketName, + s3EncryptionKeyId, + searchContextCostPerQuery, + streamTimeout, + (tieredPricing ?: JsonMissing.of()).map { it.toImmutable() }, + timeout, + tpm, + useInPassThrough, + useLitellmProxy, + vectorStoreId, + vertexCredentials, + vertexLocation, + vertexProject, + watsonxRegionName, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): LitellmParams = apply { + if (validated) { + return@apply + } + + model() + apiBase() + apiKey() + apiVersion() + autoRouterConfig() + autoRouterConfigPath() + autoRouterDefaultModel() + autoRouterEmbeddingModel() + awsAccessKeyId() + awsBedrockRuntimeEndpoint() + awsRegionName() + awsSecretAccessKey() + budgetDuration() + cacheCreationInputAudioTokenCost() + cacheCreationInputTokenCost() + cacheCreationInputTokenCostAbove1hr() + cacheCreationInputTokenCostAbove200kTokens() + cacheReadInputAudioTokenCost() + cacheReadInputTokenCost() + cacheReadInputTokenCostAbove200kTokens() + cacheReadInputTokenCostFlex() + cacheReadInputTokenCostPriority() + citationCostPerToken() + configurableClientsideAuthParams().ifPresent { it.forEach { it.validate() } } + customLlmProvider() + gcsBucketName() + inputCostPerAudioPerSecond() + inputCostPerAudioPerSecondAbove128kTokens() + inputCostPerAudioToken() + inputCostPerCharacter() + inputCostPerCharacterAbove128kTokens() + inputCostPerImage() + inputCostPerImageAbove128kTokens() + inputCostPerPixel() + inputCostPerQuery() + inputCostPerSecond() + inputCostPerToken() + inputCostPerTokenAbove128kTokens() + inputCostPerTokenAbove200kTokens() + inputCostPerTokenBatches() + inputCostPerTokenCacheHit() + inputCostPerTokenFlex() + inputCostPerTokenPriority() + inputCostPerVideoPerSecond() + inputCostPerVideoPerSecondAbove128kTokens() + inputCostPerVideoPerSecondAbove15sInterval() + inputCostPerVideoPerSecondAbove8sInterval() + litellmCredentialName() + litellmTraceId() + maxBudget() + maxFileSizeMb() + maxRetries() + mergeReasoningContentInChoices() + milvusTextField() + mockResponse().ifPresent { it.validate() } + modelInfo().ifPresent { it.validate() } + organization() + outputCostPerAudioPerSecond() + outputCostPerAudioToken() + outputCostPerCharacter() + outputCostPerCharacterAbove128kTokens() + outputCostPerImage() + outputCostPerImageToken() + outputCostPerPixel() + outputCostPerReasoningToken() + outputCostPerSecond() + outputCostPerToken() + outputCostPerTokenAbove128kTokens() + outputCostPerTokenAbove200kTokens() + outputCostPerTokenBatches() + outputCostPerTokenFlex() + outputCostPerTokenPriority() + outputCostPerVideoPerSecond() + regionName() + rpm() + s3BucketName() + s3EncryptionKeyId() + searchContextCostPerQuery().ifPresent { it.validate() } + streamTimeout().ifPresent { it.validate() } + tieredPricing().ifPresent { it.forEach { it.validate() } } + timeout().ifPresent { it.validate() } + tpm() + useInPassThrough() + useLitellmProxy() + vectorStoreId() + vertexCredentials().ifPresent { it.validate() } + vertexLocation() + vertexProject() + watsonxRegionName() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (model.asKnown().isPresent) 1 else 0) + + (if (apiBase.asKnown().isPresent) 1 else 0) + + (if (apiKey.asKnown().isPresent) 1 else 0) + + (if (apiVersion.asKnown().isPresent) 1 else 0) + + (if (autoRouterConfig.asKnown().isPresent) 1 else 0) + + (if (autoRouterConfigPath.asKnown().isPresent) 1 else 0) + + (if (autoRouterDefaultModel.asKnown().isPresent) 1 else 0) + + (if (autoRouterEmbeddingModel.asKnown().isPresent) 1 else 0) + + (if (awsAccessKeyId.asKnown().isPresent) 1 else 0) + + (if (awsBedrockRuntimeEndpoint.asKnown().isPresent) 1 else 0) + + (if (awsRegionName.asKnown().isPresent) 1 else 0) + + (if (awsSecretAccessKey.asKnown().isPresent) 1 else 0) + + (if (budgetDuration.asKnown().isPresent) 1 else 0) + + (if (cacheCreationInputAudioTokenCost.asKnown().isPresent) 1 else 0) + + (if (cacheCreationInputTokenCost.asKnown().isPresent) 1 else 0) + + (if (cacheCreationInputTokenCostAbove1hr.asKnown().isPresent) 1 else 0) + + (if (cacheCreationInputTokenCostAbove200kTokens.asKnown().isPresent) 1 else 0) + + (if (cacheReadInputAudioTokenCost.asKnown().isPresent) 1 else 0) + + (if (cacheReadInputTokenCost.asKnown().isPresent) 1 else 0) + + (if (cacheReadInputTokenCostAbove200kTokens.asKnown().isPresent) 1 else 0) + + (if (cacheReadInputTokenCostFlex.asKnown().isPresent) 1 else 0) + + (if (cacheReadInputTokenCostPriority.asKnown().isPresent) 1 else 0) + + (if (citationCostPerToken.asKnown().isPresent) 1 else 0) + + (configurableClientsideAuthParams.asKnown().getOrNull()?.sumOf { + it.validity().toInt() + } ?: 0) + + (if (customLlmProvider.asKnown().isPresent) 1 else 0) + + (if (gcsBucketName.asKnown().isPresent) 1 else 0) + + (if (inputCostPerAudioPerSecond.asKnown().isPresent) 1 else 0) + + (if (inputCostPerAudioPerSecondAbove128kTokens.asKnown().isPresent) 1 else 0) + + (if (inputCostPerAudioToken.asKnown().isPresent) 1 else 0) + + (if (inputCostPerCharacter.asKnown().isPresent) 1 else 0) + + (if (inputCostPerCharacterAbove128kTokens.asKnown().isPresent) 1 else 0) + + (if (inputCostPerImage.asKnown().isPresent) 1 else 0) + + (if (inputCostPerImageAbove128kTokens.asKnown().isPresent) 1 else 0) + + (if (inputCostPerPixel.asKnown().isPresent) 1 else 0) + + (if (inputCostPerQuery.asKnown().isPresent) 1 else 0) + + (if (inputCostPerSecond.asKnown().isPresent) 1 else 0) + + (if (inputCostPerToken.asKnown().isPresent) 1 else 0) + + (if (inputCostPerTokenAbove128kTokens.asKnown().isPresent) 1 else 0) + + (if (inputCostPerTokenAbove200kTokens.asKnown().isPresent) 1 else 0) + + (if (inputCostPerTokenBatches.asKnown().isPresent) 1 else 0) + + (if (inputCostPerTokenCacheHit.asKnown().isPresent) 1 else 0) + + (if (inputCostPerTokenFlex.asKnown().isPresent) 1 else 0) + + (if (inputCostPerTokenPriority.asKnown().isPresent) 1 else 0) + + (if (inputCostPerVideoPerSecond.asKnown().isPresent) 1 else 0) + + (if (inputCostPerVideoPerSecondAbove128kTokens.asKnown().isPresent) 1 else 0) + + (if (inputCostPerVideoPerSecondAbove15sInterval.asKnown().isPresent) 1 else 0) + + (if (inputCostPerVideoPerSecondAbove8sInterval.asKnown().isPresent) 1 else 0) + + (if (litellmCredentialName.asKnown().isPresent) 1 else 0) + + (if (litellmTraceId.asKnown().isPresent) 1 else 0) + + (if (maxBudget.asKnown().isPresent) 1 else 0) + + (if (maxFileSizeMb.asKnown().isPresent) 1 else 0) + + (if (maxRetries.asKnown().isPresent) 1 else 0) + + (if (mergeReasoningContentInChoices.asKnown().isPresent) 1 else 0) + + (if (milvusTextField.asKnown().isPresent) 1 else 0) + + (mockResponse.asKnown().getOrNull()?.validity() ?: 0) + + (modelInfo.asKnown().getOrNull()?.validity() ?: 0) + + (if (organization.asKnown().isPresent) 1 else 0) + + (if (outputCostPerAudioPerSecond.asKnown().isPresent) 1 else 0) + + (if (outputCostPerAudioToken.asKnown().isPresent) 1 else 0) + + (if (outputCostPerCharacter.asKnown().isPresent) 1 else 0) + + (if (outputCostPerCharacterAbove128kTokens.asKnown().isPresent) 1 else 0) + + (if (outputCostPerImage.asKnown().isPresent) 1 else 0) + + (if (outputCostPerImageToken.asKnown().isPresent) 1 else 0) + + (if (outputCostPerPixel.asKnown().isPresent) 1 else 0) + + (if (outputCostPerReasoningToken.asKnown().isPresent) 1 else 0) + + (if (outputCostPerSecond.asKnown().isPresent) 1 else 0) + + (if (outputCostPerToken.asKnown().isPresent) 1 else 0) + + (if (outputCostPerTokenAbove128kTokens.asKnown().isPresent) 1 else 0) + + (if (outputCostPerTokenAbove200kTokens.asKnown().isPresent) 1 else 0) + + (if (outputCostPerTokenBatches.asKnown().isPresent) 1 else 0) + + (if (outputCostPerTokenFlex.asKnown().isPresent) 1 else 0) + + (if (outputCostPerTokenPriority.asKnown().isPresent) 1 else 0) + + (if (outputCostPerVideoPerSecond.asKnown().isPresent) 1 else 0) + + (if (regionName.asKnown().isPresent) 1 else 0) + + (if (rpm.asKnown().isPresent) 1 else 0) + + (if (s3BucketName.asKnown().isPresent) 1 else 0) + + (if (s3EncryptionKeyId.asKnown().isPresent) 1 else 0) + + (searchContextCostPerQuery.asKnown().getOrNull()?.validity() ?: 0) + + (streamTimeout.asKnown().getOrNull()?.validity() ?: 0) + + (tieredPricing.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (timeout.asKnown().getOrNull()?.validity() ?: 0) + + (if (tpm.asKnown().isPresent) 1 else 0) + + (if (useInPassThrough.asKnown().isPresent) 1 else 0) + + (if (useLitellmProxy.asKnown().isPresent) 1 else 0) + + (if (vectorStoreId.asKnown().isPresent) 1 else 0) + + (vertexCredentials.asKnown().getOrNull()?.validity() ?: 0) + + (if (vertexLocation.asKnown().isPresent) 1 else 0) + + (if (vertexProject.asKnown().isPresent) 1 else 0) + + (if (watsonxRegionName.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = ConfigurableClientsideAuthParam.Deserializer::class) + @JsonSerialize(using = ConfigurableClientsideAuthParam.Serializer::class) + class ConfigurableClientsideAuthParam + private constructor( + private val string: String? = null, + private val paramsCustomAuthInput: ConfigurableClientsideParamsCustomAuthInput? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun paramsCustomAuthInput(): Optional = + Optional.ofNullable(paramsCustomAuthInput) + + fun isString(): Boolean = string != null + + fun isParamsCustomAuthInput(): Boolean = paramsCustomAuthInput != null + + fun asString(): String = string.getOrThrow("string") + + fun asParamsCustomAuthInput(): ConfigurableClientsideParamsCustomAuthInput = + paramsCustomAuthInput.getOrThrow("paramsCustomAuthInput") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + paramsCustomAuthInput != null -> + visitor.visitParamsCustomAuthInput(paramsCustomAuthInput) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): ConfigurableClientsideAuthParam = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitParamsCustomAuthInput( + paramsCustomAuthInput: ConfigurableClientsideParamsCustomAuthInput + ) { + paramsCustomAuthInput.validate() + } + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * You should usually call [Builder.apiVersion] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Used for best match union deserialization. */ - fun apiVersion(apiVersion: JsonField) = apply { this.apiVersion = apiVersion } + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 - fun awsAccessKeyId(awsAccessKeyId: String?) = - awsAccessKeyId(JsonField.ofNullable(awsAccessKeyId)) + override fun visitParamsCustomAuthInput( + paramsCustomAuthInput: ConfigurableClientsideParamsCustomAuthInput + ) = paramsCustomAuthInput.validity() - /** Alias for calling [Builder.awsAccessKeyId] with `awsAccessKeyId.orElse(null)`. */ - fun awsAccessKeyId(awsAccessKeyId: Optional) = - awsAccessKeyId(awsAccessKeyId.getOrNull()) + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ConfigurableClientsideAuthParam && + string == other.string && + paramsCustomAuthInput == other.paramsCustomAuthInput + } + + override fun hashCode(): Int = Objects.hash(string, paramsCustomAuthInput) + + override fun toString(): String = + when { + string != null -> "ConfigurableClientsideAuthParam{string=$string}" + paramsCustomAuthInput != null -> + "ConfigurableClientsideAuthParam{paramsCustomAuthInput=$paramsCustomAuthInput}" + _json != null -> "ConfigurableClientsideAuthParam{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ConfigurableClientsideAuthParam") + } + + companion object { + + @JvmStatic + fun ofString(string: String) = ConfigurableClientsideAuthParam(string = string) + + @JvmStatic + fun ofParamsCustomAuthInput( + paramsCustomAuthInput: ConfigurableClientsideParamsCustomAuthInput + ) = ConfigurableClientsideAuthParam(paramsCustomAuthInput = paramsCustomAuthInput) + } /** - * Sets [Builder.awsAccessKeyId] to an arbitrary JSON value. - * - * You should usually call [Builder.awsAccessKeyId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * An interface that defines how to map each variant of + * [ConfigurableClientsideAuthParam] to a value of type [T]. */ - fun awsAccessKeyId(awsAccessKeyId: JsonField) = apply { - this.awsAccessKeyId = awsAccessKeyId + interface Visitor { + + fun visitString(string: String): T + + fun visitParamsCustomAuthInput( + paramsCustomAuthInput: ConfigurableClientsideParamsCustomAuthInput + ): T + + /** + * Maps an unknown variant of [ConfigurableClientsideAuthParam] to a value of type + * [T]. + * + * An instance of [ConfigurableClientsideAuthParam] can contain an unknown variant + * if it was deserialized from data that doesn't match any known variant. For + * example, if the SDK is on an older version than the API, then the API may respond + * with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException( + "Unknown ConfigurableClientsideAuthParam: $json" + ) + } } - fun awsRegionName(awsRegionName: String?) = - awsRegionName(JsonField.ofNullable(awsRegionName)) + internal class Deserializer : + BaseDeserializer( + ConfigurableClientsideAuthParam::class + ) { - /** Alias for calling [Builder.awsRegionName] with `awsRegionName.orElse(null)`. */ - fun awsRegionName(awsRegionName: Optional) = - awsRegionName(awsRegionName.getOrNull()) + override fun ObjectCodec.deserialize( + node: JsonNode + ): ConfigurableClientsideAuthParam { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef< + ConfigurableClientsideParamsCustomAuthInput + >(), + ) + ?.let { + ConfigurableClientsideAuthParam( + paramsCustomAuthInput = it, + _json = json, + ) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + ConfigurableClientsideAuthParam(string = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants (e.g. deserializing from boolean). + 0 -> ConfigurableClientsideAuthParam(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } + + internal class Serializer : + BaseSerializer( + ConfigurableClientsideAuthParam::class + ) { + + override fun serialize( + value: ConfigurableClientsideAuthParam, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.paramsCustomAuthInput != null -> + generator.writeObject(value.paramsCustomAuthInput) + value._json != null -> generator.writeObject(value._json) + else -> + throw IllegalStateException("Invalid ConfigurableClientsideAuthParam") + } + } + } + + class ConfigurableClientsideParamsCustomAuthInput + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val apiBase: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("api_base") + @ExcludeMissing + apiBase: JsonField = JsonMissing.of() + ) : this(apiBase, mutableMapOf()) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun apiBase(): String = apiBase.getRequired("api_base") + + /** + * Returns the raw JSON value of [apiBase]. + * + * Unlike [apiBase], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("api_base") + @ExcludeMissing + fun _apiBase(): JsonField = apiBase + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ConfigurableClientsideParamsCustomAuthInput]. + * + * The following fields are required: + * ```java + * .apiBase() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ConfigurableClientsideParamsCustomAuthInput]. */ + class Builder internal constructor() { + + private var apiBase: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from( + configurableClientsideParamsCustomAuthInput: + ConfigurableClientsideParamsCustomAuthInput + ) = apply { + apiBase = configurableClientsideParamsCustomAuthInput.apiBase + additionalProperties = + configurableClientsideParamsCustomAuthInput.additionalProperties + .toMutableMap() + } + + fun apiBase(apiBase: String) = apiBase(JsonField.of(apiBase)) + + /** + * Sets [Builder.apiBase] to an arbitrary JSON value. + * + * You should usually call [Builder.apiBase] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun apiBase(apiBase: JsonField) = apply { this.apiBase = apiBase } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of + * [ConfigurableClientsideParamsCustomAuthInput]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .apiBase() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ConfigurableClientsideParamsCustomAuthInput = + ConfigurableClientsideParamsCustomAuthInput( + checkRequired("apiBase", apiBase), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ConfigurableClientsideParamsCustomAuthInput = apply { + if (validated) { + return@apply + } + + apiBase() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (apiBase.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ConfigurableClientsideParamsCustomAuthInput && + apiBase == other.apiBase && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(apiBase, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ConfigurableClientsideParamsCustomAuthInput{apiBase=$apiBase, additionalProperties=$additionalProperties}" + } + } + + @JsonDeserialize(using = MockResponse.Deserializer::class) + @JsonSerialize(using = MockResponse.Serializer::class) + class MockResponse + private constructor( + private val string: String? = null, + private val model: ModelResponse? = null, + private val jsonValue: JsonValue? = null, + private val _json: JsonValue? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun model(): Optional = Optional.ofNullable(model) + + fun jsonValue(): Optional = Optional.ofNullable(jsonValue) + + fun isString(): Boolean = string != null + + fun isModel(): Boolean = model != null + + fun isJsonValue(): Boolean = jsonValue != null + + fun asString(): String = string.getOrThrow("string") + + fun asModel(): ModelResponse = model.getOrThrow("model") + + fun asJsonValue(): JsonValue = jsonValue.getOrThrow("jsonValue") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + model != null -> visitor.visitModel(model) + jsonValue != null -> visitor.visitJsonValue(jsonValue) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): MockResponse = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitString(string: String) {} + + override fun visitModel(model: ModelResponse) { + model.validate() + } + + override fun visitJsonValue(jsonValue: JsonValue) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } /** - * Sets [Builder.awsRegionName] to an arbitrary JSON value. + * Returns a score indicating how many valid values are contained in this object + * recursively. * - * You should usually call [Builder.awsRegionName] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. + * Used for best match union deserialization. */ - fun awsRegionName(awsRegionName: JsonField) = apply { - this.awsRegionName = awsRegionName - } + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitString(string: String) = 1 - fun awsSecretAccessKey(awsSecretAccessKey: String?) = - awsSecretAccessKey(JsonField.ofNullable(awsSecretAccessKey)) + override fun visitModel(model: ModelResponse) = model.validity() - /** - * Alias for calling [Builder.awsSecretAccessKey] with - * `awsSecretAccessKey.orElse(null)`. - */ - fun awsSecretAccessKey(awsSecretAccessKey: Optional) = - awsSecretAccessKey(awsSecretAccessKey.getOrNull()) + override fun visitJsonValue(jsonValue: JsonValue) = 1 - /** - * Sets [Builder.awsSecretAccessKey] to an arbitrary JSON value. - * - * You should usually call [Builder.awsSecretAccessKey] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun awsSecretAccessKey(awsSecretAccessKey: JsonField) = apply { - this.awsSecretAccessKey = awsSecretAccessKey + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is MockResponse && + string == other.string && + model == other.model && + jsonValue == other.jsonValue } - fun budgetDuration(budgetDuration: String?) = - budgetDuration(JsonField.ofNullable(budgetDuration)) + override fun hashCode(): Int = Objects.hash(string, model, jsonValue) - /** Alias for calling [Builder.budgetDuration] with `budgetDuration.orElse(null)`. */ - fun budgetDuration(budgetDuration: Optional) = - budgetDuration(budgetDuration.getOrNull()) + override fun toString(): String = + when { + string != null -> "MockResponse{string=$string}" + model != null -> "MockResponse{model=$model}" + jsonValue != null -> "MockResponse{jsonValue=$jsonValue}" + _json != null -> "MockResponse{_unknown=$_json}" + else -> throw IllegalStateException("Invalid MockResponse") + } - /** - * Sets [Builder.budgetDuration] to an arbitrary JSON value. - * - * You should usually call [Builder.budgetDuration] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun budgetDuration(budgetDuration: JsonField) = apply { - this.budgetDuration = budgetDuration - } + companion object { - fun configurableClientsideAuthParams( - configurableClientsideAuthParams: List? - ) = - configurableClientsideAuthParams( - JsonField.ofNullable(configurableClientsideAuthParams) - ) + @JvmStatic fun ofString(string: String) = MockResponse(string = string) - /** - * Alias for calling [Builder.configurableClientsideAuthParams] with - * `configurableClientsideAuthParams.orElse(null)`. - */ - fun configurableClientsideAuthParams( - configurableClientsideAuthParams: Optional> - ) = configurableClientsideAuthParams(configurableClientsideAuthParams.getOrNull()) + @JvmStatic fun ofModel(model: ModelResponse) = MockResponse(model = model) - /** - * Sets [Builder.configurableClientsideAuthParams] to an arbitrary JSON value. - * - * You should usually call [Builder.configurableClientsideAuthParams] with a well-typed - * `List` value instead. This method is primarily for - * setting the field to an undocumented or not yet supported value. - */ - fun configurableClientsideAuthParams( - configurableClientsideAuthParams: JsonField> - ) = apply { - this.configurableClientsideAuthParams = - configurableClientsideAuthParams.map { it.toMutableList() } + @JvmStatic + fun ofJsonValue(jsonValue: JsonValue) = MockResponse(jsonValue = jsonValue) } /** - * Adds a single [ConfigurableClientsideAuthParam] to - * [configurableClientsideAuthParams]. - * - * @throws IllegalStateException if the field was previously set to a non-list. + * An interface that defines how to map each variant of [MockResponse] to a value of + * type [T]. */ - fun addConfigurableClientsideAuthParam( - configurableClientsideAuthParam: ConfigurableClientsideAuthParam - ) = apply { - configurableClientsideAuthParams = - (configurableClientsideAuthParams ?: JsonField.of(mutableListOf())).also { - checkKnown("configurableClientsideAuthParams", it) - .add(configurableClientsideAuthParam) - } + interface Visitor { + + fun visitString(string: String): T + + fun visitModel(model: ModelResponse): T + + fun visitJsonValue(jsonValue: JsonValue): T + + /** + * Maps an unknown variant of [MockResponse] to a value of type [T]. + * + * An instance of [MockResponse] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if the + * SDK is on an older version than the API, then the API may respond with new + * variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown MockResponse: $json") + } } - /** - * Alias for calling [addConfigurableClientsideAuthParam] with - * `ConfigurableClientsideAuthParam.ofString(string)`. - */ - fun addConfigurableClientsideAuthParam(string: String) = - addConfigurableClientsideAuthParam(ConfigurableClientsideAuthParam.ofString(string)) + internal class Deserializer : BaseDeserializer(MockResponse::class) { - /** - * Alias for calling [addConfigurableClientsideAuthParam] with - * `ConfigurableClientsideAuthParam.ofParamsCustomAuth(paramsCustomAuth)`. - */ - fun addConfigurableClientsideAuthParam( - paramsCustomAuth: ConfigurableClientsideParamsCustomAuth - ) = - addConfigurableClientsideAuthParam( - ConfigurableClientsideAuthParam.ofParamsCustomAuth(paramsCustomAuth) - ) + override fun ObjectCodec.deserialize(node: JsonNode): MockResponse { + val json = JsonValue.fromJsonNode(node) - fun customLlmProvider(customLlmProvider: String?) = - customLlmProvider(JsonField.ofNullable(customLlmProvider)) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + MockResponse(model = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + MockResponse(string = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + MockResponse(jsonValue = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible + // with all the possible variants. + 0 -> MockResponse(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the + // first completely valid match, or simply the first match if none are + // completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } - /** - * Alias for calling [Builder.customLlmProvider] with `customLlmProvider.orElse(null)`. - */ - fun customLlmProvider(customLlmProvider: Optional) = - customLlmProvider(customLlmProvider.getOrNull()) + internal class Serializer : BaseSerializer(MockResponse::class) { - /** - * Sets [Builder.customLlmProvider] to an arbitrary JSON value. - * - * You should usually call [Builder.customLlmProvider] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun customLlmProvider(customLlmProvider: JsonField) = apply { - this.customLlmProvider = customLlmProvider + override fun serialize( + value: MockResponse, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.model != null -> generator.writeObject(value.model) + value.jsonValue != null -> generator.writeObject(value.jsonValue) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid MockResponse") + } + } } - fun inputCostPerSecond(inputCostPerSecond: Double?) = - inputCostPerSecond(JsonField.ofNullable(inputCostPerSecond)) + class ModelResponse + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val id: JsonField, + private val choices: JsonField>, + private val created: JsonField, + private val object_: JsonField, + private val model: JsonField, + private val systemFingerprint: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("choices") + @ExcludeMissing + choices: JsonField> = JsonMissing.of(), + @JsonProperty("created") + @ExcludeMissing + created: JsonField = JsonMissing.of(), + @JsonProperty("object") + @ExcludeMissing + object_: JsonField = JsonMissing.of(), + @JsonProperty("model") + @ExcludeMissing + model: JsonField = JsonMissing.of(), + @JsonProperty("system_fingerprint") + @ExcludeMissing + systemFingerprint: JsonField = JsonMissing.of(), + ) : this(id, choices, created, object_, model, systemFingerprint, mutableMapOf()) - /** - * Alias for [Builder.inputCostPerSecond]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun inputCostPerSecond(inputCostPerSecond: Double) = - inputCostPerSecond(inputCostPerSecond as Double?) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun id(): String = id.getRequired("id") - /** - * Alias for calling [Builder.inputCostPerSecond] with - * `inputCostPerSecond.orElse(null)`. - */ - fun inputCostPerSecond(inputCostPerSecond: Optional) = - inputCostPerSecond(inputCostPerSecond.getOrNull()) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun choices(): List = choices.getRequired("choices") - /** - * Sets [Builder.inputCostPerSecond] to an arbitrary JSON value. - * - * You should usually call [Builder.inputCostPerSecond] with a well-typed [Double] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun inputCostPerSecond(inputCostPerSecond: JsonField) = apply { - this.inputCostPerSecond = inputCostPerSecond - } + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun created(): Long = created.getRequired("created") - fun inputCostPerToken(inputCostPerToken: Double?) = - inputCostPerToken(JsonField.ofNullable(inputCostPerToken)) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ + fun object_(): String = object_.getRequired("object") - /** - * Alias for [Builder.inputCostPerToken]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun inputCostPerToken(inputCostPerToken: Double) = - inputCostPerToken(inputCostPerToken as Double?) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun model(): Optional = model.getOptional("model") - /** - * Alias for calling [Builder.inputCostPerToken] with `inputCostPerToken.orElse(null)`. - */ - fun inputCostPerToken(inputCostPerToken: Optional) = - inputCostPerToken(inputCostPerToken.getOrNull()) + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun systemFingerprint(): Optional = + systemFingerprint.getOptional("system_fingerprint") - /** - * Sets [Builder.inputCostPerToken] to an arbitrary JSON value. - * - * You should usually call [Builder.inputCostPerToken] with a well-typed [Double] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun inputCostPerToken(inputCostPerToken: JsonField) = apply { - this.inputCostPerToken = inputCostPerToken - } + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - fun llmTraceId(llmTraceId: String?) = llmTraceId(JsonField.ofNullable(llmTraceId)) + /** + * Returns the raw JSON value of [choices]. + * + * Unlike [choices], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("choices") + @ExcludeMissing + fun _choices(): JsonField> = choices - /** Alias for calling [Builder.llmTraceId] with `llmTraceId.orElse(null)`. */ - fun llmTraceId(llmTraceId: Optional) = llmTraceId(llmTraceId.getOrNull()) + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created - /** - * Sets [Builder.llmTraceId] to an arbitrary JSON value. - * - * You should usually call [Builder.llmTraceId] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun llmTraceId(llmTraceId: JsonField) = apply { this.llmTraceId = llmTraceId } + /** + * Returns the raw JSON value of [object_]. + * + * Unlike [object_], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("object") @ExcludeMissing fun _object_(): JsonField = object_ - fun maxBudget(maxBudget: Double?) = maxBudget(JsonField.ofNullable(maxBudget)) + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model - /** - * Alias for [Builder.maxBudget]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun maxBudget(maxBudget: Double) = maxBudget(maxBudget as Double?) + /** + * Returns the raw JSON value of [systemFingerprint]. + * + * Unlike [systemFingerprint], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("system_fingerprint") + @ExcludeMissing + fun _systemFingerprint(): JsonField = systemFingerprint - /** Alias for calling [Builder.maxBudget] with `maxBudget.orElse(null)`. */ - fun maxBudget(maxBudget: Optional) = maxBudget(maxBudget.getOrNull()) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** - * Sets [Builder.maxBudget] to an arbitrary JSON value. - * - * You should usually call [Builder.maxBudget] with a well-typed [Double] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxBudget(maxBudget: JsonField) = apply { this.maxBudget = maxBudget } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ModelResponse]. + * + * The following fields are required: + * ```java + * .id() + * .choices() + * .created() + * .object_() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - fun maxFileSizeMb(maxFileSizeMb: Double?) = - maxFileSizeMb(JsonField.ofNullable(maxFileSizeMb)) + /** A builder for [ModelResponse]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var choices: JsonField>? = null + private var created: JsonField? = null + private var object_: JsonField? = null + private var model: JsonField = JsonMissing.of() + private var systemFingerprint: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelResponse: ModelResponse) = apply { + id = modelResponse.id + choices = modelResponse.choices.map { it.toMutableList() } + created = modelResponse.created + object_ = modelResponse.object_ + model = modelResponse.model + systemFingerprint = modelResponse.systemFingerprint + additionalProperties = modelResponse.additionalProperties.toMutableMap() + } - /** - * Alias for [Builder.maxFileSizeMb]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun maxFileSizeMb(maxFileSizeMb: Double) = maxFileSizeMb(maxFileSizeMb as Double?) + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + fun choices(choices: List) = choices(JsonField.of(choices)) + + /** + * Sets [Builder.choices] to an arbitrary JSON value. + * + * You should usually call [Builder.choices] with a well-typed `List` + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun choices(choices: JsonField>) = apply { + this.choices = choices.map { it.toMutableList() } + } - /** Alias for calling [Builder.maxFileSizeMb] with `maxFileSizeMb.orElse(null)`. */ - fun maxFileSizeMb(maxFileSizeMb: Optional) = - maxFileSizeMb(maxFileSizeMb.getOrNull()) + /** + * Adds a single [Choice] to [choices]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addChoice(choice: Choice) = apply { + choices = + (choices ?: JsonField.of(mutableListOf())).also { + checkKnown("choices", it).add(choice) + } + } - /** - * Sets [Builder.maxFileSizeMb] to an arbitrary JSON value. - * - * You should usually call [Builder.maxFileSizeMb] with a well-typed [Double] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxFileSizeMb(maxFileSizeMb: JsonField) = apply { - this.maxFileSizeMb = maxFileSizeMb - } + /** Alias for calling [addChoice] with `Choice.ofChoices(choices)`. */ + fun addChoice(choices: Choice.Choices) = addChoice(Choice.ofChoices(choices)) + + /** + * Alias for calling [addChoice] with + * `Choice.ofStreamingChoices(streamingChoices)`. + */ + fun addChoice(streamingChoices: Choice.StreamingChoices) = + addChoice(Choice.ofStreamingChoices(streamingChoices)) + + fun created(created: Long) = created(JsonField.of(created)) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + fun object_(object_: String) = object_(JsonField.of(object_)) + + /** + * Sets [Builder.object_] to an arbitrary JSON value. + * + * You should usually call [Builder.object_] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + fun model(model: String?) = model(JsonField.ofNullable(model)) + + /** Alias for calling [Builder.model] with `model.orElse(null)`. */ + fun model(model: Optional) = model(model.getOrNull()) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun systemFingerprint(systemFingerprint: String?) = + systemFingerprint(JsonField.ofNullable(systemFingerprint)) + + /** + * Alias for calling [Builder.systemFingerprint] with + * `systemFingerprint.orElse(null)`. + */ + fun systemFingerprint(systemFingerprint: Optional) = + systemFingerprint(systemFingerprint.getOrNull()) + + /** + * Sets [Builder.systemFingerprint] to an arbitrary JSON value. + * + * You should usually call [Builder.systemFingerprint] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun systemFingerprint(systemFingerprint: JsonField) = apply { + this.systemFingerprint = systemFingerprint + } - fun maxRetries(maxRetries: Long?) = maxRetries(JsonField.ofNullable(maxRetries)) + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - /** - * Alias for [Builder.maxRetries]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun maxRetries(maxRetries: Long) = maxRetries(maxRetries as Long?) + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - /** Alias for calling [Builder.maxRetries] with `maxRetries.orElse(null)`. */ - fun maxRetries(maxRetries: Optional) = maxRetries(maxRetries.getOrNull()) + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } - /** - * Sets [Builder.maxRetries] to an arbitrary JSON value. - * - * You should usually call [Builder.maxRetries] with a well-typed [Long] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun maxRetries(maxRetries: JsonField) = apply { this.maxRetries = maxRetries } + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } - fun mergeReasoningContentInChoices(mergeReasoningContentInChoices: Boolean?) = - mergeReasoningContentInChoices(JsonField.ofNullable(mergeReasoningContentInChoices)) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - /** - * Alias for [Builder.mergeReasoningContentInChoices]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun mergeReasoningContentInChoices(mergeReasoningContentInChoices: Boolean) = - mergeReasoningContentInChoices(mergeReasoningContentInChoices as Boolean?) + /** + * Returns an immutable instance of [ModelResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .choices() + * .created() + * .object_() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ModelResponse = + ModelResponse( + checkRequired("id", id), + checkRequired("choices", choices).map { it.toImmutable() }, + checkRequired("created", created), + checkRequired("object_", object_), + model, + systemFingerprint, + additionalProperties.toMutableMap(), + ) + } - /** - * Alias for calling [Builder.mergeReasoningContentInChoices] with - * `mergeReasoningContentInChoices.orElse(null)`. - */ - fun mergeReasoningContentInChoices(mergeReasoningContentInChoices: Optional) = - mergeReasoningContentInChoices(mergeReasoningContentInChoices.getOrNull()) + private var validated: Boolean = false - /** - * Sets [Builder.mergeReasoningContentInChoices] to an arbitrary JSON value. - * - * You should usually call [Builder.mergeReasoningContentInChoices] with a well-typed - * [Boolean] value instead. This method is primarily for setting the field to an - * undocumented or not yet supported value. - */ - fun mergeReasoningContentInChoices(mergeReasoningContentInChoices: JsonField) = - apply { - this.mergeReasoningContentInChoices = mergeReasoningContentInChoices + fun validate(): ModelResponse = apply { + if (validated) { + return@apply + } + + id() + choices().forEach { it.validate() } + created() + object_() + model() + systemFingerprint() + validated = true } - fun modelInfo(modelInfo: JsonValue) = apply { this.modelInfo = modelInfo } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } - fun organization(organization: String?) = - organization(JsonField.ofNullable(organization)) + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (choices.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (object_.asKnown().isPresent) 1 else 0) + + (if (model.asKnown().isPresent) 1 else 0) + + (if (systemFingerprint.asKnown().isPresent) 1 else 0) + + @JsonDeserialize(using = Choice.Deserializer::class) + @JsonSerialize(using = Choice.Serializer::class) + class Choice + private constructor( + private val choices: Choices? = null, + private val streamingChoices: StreamingChoices? = null, + private val _json: JsonValue? = null, + ) { - /** Alias for calling [Builder.organization] with `organization.orElse(null)`. */ - fun organization(organization: Optional) = - organization(organization.getOrNull()) + fun choices(): Optional = Optional.ofNullable(choices) - /** - * Sets [Builder.organization] to an arbitrary JSON value. - * - * You should usually call [Builder.organization] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun organization(organization: JsonField) = apply { - this.organization = organization - } + fun streamingChoices(): Optional = + Optional.ofNullable(streamingChoices) - fun outputCostPerSecond(outputCostPerSecond: Double?) = - outputCostPerSecond(JsonField.ofNullable(outputCostPerSecond)) + fun isChoices(): Boolean = choices != null - /** - * Alias for [Builder.outputCostPerSecond]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun outputCostPerSecond(outputCostPerSecond: Double) = - outputCostPerSecond(outputCostPerSecond as Double?) + fun isStreamingChoices(): Boolean = streamingChoices != null - /** - * Alias for calling [Builder.outputCostPerSecond] with - * `outputCostPerSecond.orElse(null)`. - */ - fun outputCostPerSecond(outputCostPerSecond: Optional) = - outputCostPerSecond(outputCostPerSecond.getOrNull()) + fun asChoices(): Choices = choices.getOrThrow("choices") - /** - * Sets [Builder.outputCostPerSecond] to an arbitrary JSON value. - * - * You should usually call [Builder.outputCostPerSecond] with a well-typed [Double] - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun outputCostPerSecond(outputCostPerSecond: JsonField) = apply { - this.outputCostPerSecond = outputCostPerSecond - } + fun asStreamingChoices(): StreamingChoices = + streamingChoices.getOrThrow("streamingChoices") - fun outputCostPerToken(outputCostPerToken: Double?) = - outputCostPerToken(JsonField.ofNullable(outputCostPerToken)) + fun _json(): Optional = Optional.ofNullable(_json) - /** - * Alias for [Builder.outputCostPerToken]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun outputCostPerToken(outputCostPerToken: Double) = - outputCostPerToken(outputCostPerToken as Double?) + fun accept(visitor: Visitor): T = + when { + choices != null -> visitor.visitChoices(choices) + streamingChoices != null -> + visitor.visitStreamingChoices(streamingChoices) + else -> visitor.unknown(_json) + } - /** - * Alias for calling [Builder.outputCostPerToken] with - * `outputCostPerToken.orElse(null)`. - */ - fun outputCostPerToken(outputCostPerToken: Optional) = - outputCostPerToken(outputCostPerToken.getOrNull()) + private var validated: Boolean = false - /** - * Sets [Builder.outputCostPerToken] to an arbitrary JSON value. - * - * You should usually call [Builder.outputCostPerToken] with a well-typed [Double] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun outputCostPerToken(outputCostPerToken: JsonField) = apply { - this.outputCostPerToken = outputCostPerToken - } + fun validate(): Choice = apply { + if (validated) { + return@apply + } - fun regionName(regionName: String?) = regionName(JsonField.ofNullable(regionName)) + accept( + object : Visitor { + override fun visitChoices(choices: Choices) { + choices.validate() + } + + override fun visitStreamingChoices( + streamingChoices: StreamingChoices + ) { + streamingChoices.validate() + } + } + ) + validated = true + } - /** Alias for calling [Builder.regionName] with `regionName.orElse(null)`. */ - fun regionName(regionName: Optional) = regionName(regionName.getOrNull()) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } - /** - * Sets [Builder.regionName] to an arbitrary JSON value. - * - * You should usually call [Builder.regionName] with a well-typed [String] value - * instead. This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun regionName(regionName: JsonField) = apply { this.regionName = regionName } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitChoices(choices: Choices) = choices.validity() + + override fun visitStreamingChoices( + streamingChoices: StreamingChoices + ) = streamingChoices.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun rpm(rpm: Long?) = rpm(JsonField.ofNullable(rpm)) + return other is Choice && + choices == other.choices && + streamingChoices == other.streamingChoices + } - /** - * Alias for [Builder.rpm]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun rpm(rpm: Long) = rpm(rpm as Long?) + override fun hashCode(): Int = Objects.hash(choices, streamingChoices) - /** Alias for calling [Builder.rpm] with `rpm.orElse(null)`. */ - fun rpm(rpm: Optional) = rpm(rpm.getOrNull()) + override fun toString(): String = + when { + choices != null -> "Choice{choices=$choices}" + streamingChoices != null -> "Choice{streamingChoices=$streamingChoices}" + _json != null -> "Choice{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Choice") + } - /** - * Sets [Builder.rpm] to an arbitrary JSON value. - * - * You should usually call [Builder.rpm] with a well-typed [Long] value instead. This - * method is primarily for setting the field to an undocumented or not yet supported - * value. - */ - fun rpm(rpm: JsonField) = apply { this.rpm = rpm } + companion object { - fun streamTimeout(streamTimeout: StreamTimeout?) = - streamTimeout(JsonField.ofNullable(streamTimeout)) + @JvmStatic fun ofChoices(choices: Choices) = Choice(choices = choices) - /** Alias for calling [Builder.streamTimeout] with `streamTimeout.orElse(null)`. */ - fun streamTimeout(streamTimeout: Optional) = - streamTimeout(streamTimeout.getOrNull()) + @JvmStatic + fun ofStreamingChoices(streamingChoices: StreamingChoices) = + Choice(streamingChoices = streamingChoices) + } - /** - * Sets [Builder.streamTimeout] to an arbitrary JSON value. - * - * You should usually call [Builder.streamTimeout] with a well-typed [StreamTimeout] - * value instead. This method is primarily for setting the field to an undocumented or - * not yet supported value. - */ - fun streamTimeout(streamTimeout: JsonField) = apply { - this.streamTimeout = streamTimeout - } + /** + * An interface that defines how to map each variant of [Choice] to a value of + * type [T]. + */ + interface Visitor { + + fun visitChoices(choices: Choices): T + + fun visitStreamingChoices(streamingChoices: StreamingChoices): T + + /** + * Maps an unknown variant of [Choice] to a value of type [T]. + * + * An instance of [Choice] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, + * if the SDK is on an older version than the API, then the API may respond + * with new variants that the SDK is unaware of. + * + * @throws HanzoInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw HanzoInvalidDataException("Unknown Choice: $json") + } + } - /** Alias for calling [streamTimeout] with `StreamTimeout.ofNumber(number)`. */ - fun streamTimeout(number: Double) = streamTimeout(StreamTimeout.ofNumber(number)) + internal class Deserializer : BaseDeserializer(Choice::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Choice { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Choice(choices = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef()) + ?.let { Choice(streamingChoices = it, _json = json) }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely + // incompatible with all the possible variants (e.g. deserializing + // from boolean). + 0 -> Choice(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then + // use the first completely valid match, or simply the first match + // if none are completely valid. + else -> + bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } + } + } - /** Alias for calling [streamTimeout] with `StreamTimeout.ofString(string)`. */ - fun streamTimeout(string: String) = streamTimeout(StreamTimeout.ofString(string)) + internal class Serializer : BaseSerializer(Choice::class) { - fun timeout(timeout: Timeout?) = timeout(JsonField.ofNullable(timeout)) + override fun serialize( + value: Choice, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.choices != null -> generator.writeObject(value.choices) + value.streamingChoices != null -> + generator.writeObject(value.streamingChoices) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Choice") + } + } + } - /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ - fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) + class Choices + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val finishReason: JsonField, + private val index: JsonField, + private val message: JsonField, + private val logprobs: JsonField, + private val providerSpecificFields: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("finish_reason") + @ExcludeMissing + finishReason: JsonField = JsonMissing.of(), + @JsonProperty("index") + @ExcludeMissing + index: JsonField = JsonMissing.of(), + @JsonProperty("message") + @ExcludeMissing + message: JsonField = JsonMissing.of(), + @JsonProperty("logprobs") + @ExcludeMissing + logprobs: JsonField = JsonMissing.of(), + @JsonProperty("provider_specific_fields") + @ExcludeMissing + providerSpecificFields: JsonField = + JsonMissing.of(), + ) : this( + finishReason, + index, + message, + logprobs, + providerSpecificFields, + mutableMapOf(), + ) + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun finishReason(): String = finishReason.getRequired("finish_reason") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun index(): Long = index.getRequired("index") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ + fun message(): Message = message.getRequired("message") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun logprobs(): Optional = logprobs.getOptional("logprobs") + + /** + * @throws HanzoInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun providerSpecificFields(): Optional = + providerSpecificFields.getOptional("provider_specific_fields") + + /** + * Returns the raw JSON value of [finishReason]. + * + * Unlike [finishReason], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("finish_reason") + @ExcludeMissing + fun _finishReason(): JsonField = finishReason + + /** + * Returns the raw JSON value of [index]. + * + * Unlike [index], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("index") @ExcludeMissing fun _index(): JsonField = index + + /** + * Returns the raw JSON value of [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("message") + @ExcludeMissing + fun _message(): JsonField = message + + /** + * Returns the raw JSON value of [logprobs]. + * + * Unlike [logprobs], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("logprobs") + @ExcludeMissing + fun _logprobs(): JsonField = logprobs + + /** + * Returns the raw JSON value of [providerSpecificFields]. + * + * Unlike [providerSpecificFields], this method doesn't throw if the JSON + * field has an unexpected type. + */ + @JsonProperty("provider_specific_fields") + @ExcludeMissing + fun _providerSpecificFields(): JsonField = + providerSpecificFields + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** - * Sets [Builder.timeout] to an arbitrary JSON value. - * - * You should usually call [Builder.timeout] with a well-typed [Timeout] value instead. - * This method is primarily for setting the field to an undocumented or not yet - * supported value. - */ - fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Choices]. + * + * The following fields are required: + * ```java + * .finishReason() + * .index() + * .message() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - /** Alias for calling [timeout] with `Timeout.ofNumber(number)`. */ - fun timeout(number: Double) = timeout(Timeout.ofNumber(number)) + /** A builder for [Choices]. */ + class Builder internal constructor() { + + private var finishReason: JsonField? = null + private var index: JsonField? = null + private var message: JsonField? = null + private var logprobs: JsonField = JsonMissing.of() + private var providerSpecificFields: JsonField = + JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(choices: Choices) = apply { + finishReason = choices.finishReason + index = choices.index + message = choices.message + logprobs = choices.logprobs + providerSpecificFields = choices.providerSpecificFields + additionalProperties = choices.additionalProperties.toMutableMap() + } + + fun finishReason(finishReason: String) = + finishReason(JsonField.of(finishReason)) + + /** + * Sets [Builder.finishReason] to an arbitrary JSON value. + * + * You should usually call [Builder.finishReason] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun finishReason(finishReason: JsonField) = apply { + this.finishReason = finishReason + } + + fun index(index: Long) = index(JsonField.of(index)) + + /** + * Sets [Builder.index] to an arbitrary JSON value. + * + * You should usually call [Builder.index] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun index(index: JsonField) = apply { this.index = index } + + fun message(message: Message) = message(JsonField.of(message)) + + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [Message] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun message(message: JsonField) = apply { + this.message = message + } + + fun logprobs(logprobs: Logprobs?) = + logprobs(JsonField.ofNullable(logprobs)) + + /** + * Alias for calling [Builder.logprobs] with `logprobs.orElse(null)`. + */ + fun logprobs(logprobs: Optional) = + logprobs(logprobs.getOrNull()) + + /** + * Sets [Builder.logprobs] to an arbitrary JSON value. + * + * You should usually call [Builder.logprobs] with a well-typed + * [Logprobs] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun logprobs(logprobs: JsonField) = apply { + this.logprobs = logprobs + } + + /** Alias for calling [logprobs] with `Logprobs.ofChoice(choice)`. */ + fun logprobs(choice: Logprobs.ChoiceLogprobs) = + logprobs(Logprobs.ofChoice(choice)) + + /** + * Alias for calling [logprobs] with `Logprobs.ofJsonValue(jsonValue)`. + */ + fun logprobs(jsonValue: JsonValue) = + logprobs(Logprobs.ofJsonValue(jsonValue)) + + fun providerSpecificFields( + providerSpecificFields: ProviderSpecificFields? + ) = providerSpecificFields(JsonField.ofNullable(providerSpecificFields)) + + /** + * Alias for calling [Builder.providerSpecificFields] with + * `providerSpecificFields.orElse(null)`. + */ + fun providerSpecificFields( + providerSpecificFields: Optional + ) = providerSpecificFields(providerSpecificFields.getOrNull()) + + /** + * Sets [Builder.providerSpecificFields] to an arbitrary JSON value. + * + * You should usually call [Builder.providerSpecificFields] with a + * well-typed [ProviderSpecificFields] value instead. This method is + * primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun providerSpecificFields( + providerSpecificFields: JsonField + ) = apply { this.providerSpecificFields = providerSpecificFields } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Choices]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .finishReason() + * .index() + * .message() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Choices = + Choices( + checkRequired("finishReason", finishReason), + checkRequired("index", index), + checkRequired("message", message), + logprobs, + providerSpecificFields, + additionalProperties.toMutableMap(), + ) + } - /** Alias for calling [timeout] with `Timeout.ofString(string)`. */ - fun timeout(string: String) = timeout(Timeout.ofString(string)) + private var validated: Boolean = false - fun tpm(tpm: Long?) = tpm(JsonField.ofNullable(tpm)) + fun validate(): Choices = apply { + if (validated) { + return@apply + } - /** - * Alias for [Builder.tpm]. - * - * This unboxed primitive overload exists for backwards compatibility. - */ - fun tpm(tpm: Long) = tpm(tpm as Long?) + finishReason() + index() + message().validate() + logprobs().ifPresent { it.validate() } + providerSpecificFields().ifPresent { it.validate() } + validated = true + } - /** Alias for calling [Builder.tpm] with `tpm.orElse(null)`. */ - fun tpm(tpm: Optional) = tpm(tpm.getOrNull()) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: HanzoInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (finishReason.asKnown().isPresent) 1 else 0) + + (if (index.asKnown().isPresent) 1 else 0) + + (message.asKnown().getOrNull()?.validity() ?: 0) + + (logprobs.asKnown().getOrNull()?.validity() ?: 0) + + (providerSpecificFields.asKnown().getOrNull()?.validity() ?: 0) + + class Message + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val content: JsonField, + private val functionCall: JsonField, + private val role: JsonField, + private val toolCalls: JsonField>, + private val annotations: JsonField>, + private val audio: JsonField